-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeTemplate.java
64 lines (53 loc) · 1.25 KB
/
BinaryTreeTemplate.java
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
package org.geeksforgeeks.binarytree;
/**
*
* @author Shiva
*
* @param <Item>
*/
public class BinaryTreeTemplate<Item extends Comparable<Item>> {
private Node root;
class Node {
private Item key;
private Node left, right;
public Node(Item key) {
this.key = key;
}
}
public void insert(Item key) {
if(key == null)
return;
root = insert(root, key);
}
private BinaryTreeTemplate<Item>.Node insert(BinaryTreeTemplate<Item>.Node root2,
Item key) {
if (root2 == null)
return new Node(key);
int cmp = key.compareTo(root2.key);
if(cmp <= 0)
root2.left = insert(root2.left, key);
else
root2.right = insert(root2.right, key);
return root2;
}
public void inOrderTraversal() {
inOrderTraversal(root);
}
private void inOrderTraversal(BinaryTreeTemplate<Item>.Node root) {
if (root == null) return;
inOrderTraversal(root.left);
System.out.print(root.key + " ");
inOrderTraversal(root.right);
}
public static void main(String[] args) {
BinaryTreeTemplate<Integer> bt = new BinaryTreeTemplate<Integer>();
bt.insert(5);
bt.insert(3);
bt.insert(8);
bt.insert(1);
bt.insert(4);
bt.insert(6);
bt.insert(10);
bt.inOrderTraversal();
}
}