-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertIntoBinaryTree.java
More file actions
60 lines (51 loc) · 1.43 KB
/
Copy pathInsertIntoBinaryTree.java
File metadata and controls
60 lines (51 loc) · 1.43 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
//Given an element insert the element into the binary tree and return the root of the tree
public class InsertIntoBinaryTree extends BinaryTree {
public static Node InsertIteratively(Node root, int element) {
Node current = null;
// If there is no tree, than new element is the root
if (root == null) {
current = new Node(element);
return current;
} else {
current = root;
}
// Find the position in the tree where the new Node fits
while (true) {
// traverse left if the new element is less than the current one
if (current.data < element) {
if (current.right != null)
current = current.right;
else
break;
}
// traverse right if the new element is greater that the current one
else if (current.data > element) {
if (current.left != null)
current = current.left;
else
break;
}
}
// Current represent the parent of the new element
if (current.data > element)
current.left = new Node(element);
else
current.right = new Node(element);
// return the root
return root;
}
public static Node InsertRecursively(Node root, int element) {
if(root == null) {
root = new Node(element);
return root;
}
if(root.data < element)
return InsertRecursively(root.left, element);
// if(root.data > element)
else
return InsertIteratively(root.right, element);
}
public static void main(String[] args) {
InsertRecursively(BinaryTree1(), 200);
}
}