Repository navigation
Expand file tree
/
Copy pathMainClass.java
More file actions
105 lines (84 loc) · 2.41 KB
/
Copy pathMainClass.java
File metadata and controls
105 lines (84 loc) · 2.41 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package binarySearchTree1;
import binaryTree3.MainClass.TreeNode;
public class MainClass {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public TreeNode insertIntoBST(TreeNode root, int key) {
if(root == null) return new TreeNode(key);
if(key > root.val) {
root.right = insertIntoBST(root.right, key);
} else if(key < root.val) {
root.left = insertIntoBST(root.left, key);
}
return root;
}
// public TreeNode insertIntoBST(TreeNode root, int key) {
// TreeNode parent = null, cur = root;
// while(cur != null) {
// if(key > cur.val) {
// parent = cur;
// cur = cur.right;
// } else if(key < cur.val) {
// parent = cur;
// cur = cur.left;
// }
// }
// TreeNode newNode = new TreeNode(key);
// if(parent == null) return newNode;
// if(key > parent.val) {
// parent.right = newNode;
// } else if(key < parent.val) {
// parent.left = newNode;
// }
// return root;
// }
static boolean isPresent(Node root, int key) {
if(root == null) return false;
System.out.println(root.data);
if(root.data == key) return true;
if(key > root.data) {
return isPresent(root.right, key);
}
return isPresent(root.left, key);
}
static boolean isPresentIterative(Node root, int key) {
Node cur = root;
while(cur != null) {
if(cur.data == key) return true;
if(key > cur.data) cur = cur.right;
else cur = cur.left;
}
return false;
}
public static void main(String[] args) {
Node root = new Node(50);
root.left = new Node(30);
root.right = new Node(80);
root.left.left = new Node(20);
root.left.right = new Node(40);
root.right.left = new Node(70);
root.right.right = new Node(100);
root.right.left.left = new Node(60);
int key = 60;
// System.out.println(isPresent(root, key));
//
System.out.println(isPresentIterative(root, key));
}
}
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
}
}