-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelement-in-tree.java
More file actions
78 lines (72 loc) · 1.48 KB
/
Copy pathelement-in-tree.java
File metadata and controls
78 lines (72 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// hackerrank
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;
public class Solution {
private static class Node {
Node left, right;
int data;
Node(int newData) {
left = right = null;
data = newData;
}
}
private static Node insert(Node node, int data) {
if (node==null) {
node = new Node(data);
}
else {
if (data <= node.data) {
node.left = insert(node.left, data);
}
else {
node.right = insert(node.right, data);
}
}
return(node);
}
public static void main(String [] args) throws Exception{
Scanner in = new Scanner(System.in);
Node _root;
int root_i=0, root_cnt = 0, root_num = 0;
root_cnt = in.nextInt();
_root=null;
for(root_i = 0; root_i < root_cnt; root_i++){
root_num = in.nextInt();
if( root_i == 0)
_root = new Node(root_num);
else
insert(_root, root_num);
}
int _x = in.nextInt();
System.out.println(isPresent(_root,_x));
return;
}
private static int isPresent(Node root, int val){
/* For your reference
class Node {
Node left, right;
int data;
Node(int newData) {
left = right = null;
data = newData;
}
}
*/
if (root == null){
return 0;
}
Node tmp = root;
while(tmp != null){
if(tmp.data == val)
return 1;
if (tmp.data > val)
tmp = tmp.left;
else
tmp = tmp.right;
}
return 0;
}
}