1package MyPackage;
2
3public class Tree {
4 static class Node {
5 int value;
6 Node left, right;
7
8 Node(int value){
9 this.value = value;
10 left = null;
11 right = null;
12 }
13 }
14
15 public void insert(Node node, int value) {
16 if (value < node.value) {
17 if (node.left != null) {
18 insert(node.left, value);
19 } else {
20 System.out.println(" Inserted " + value + " to left of " + node.value);
21 node.left = new Node(value);
22 }
23 } else if (value > node.value) {
24 if (node.right != null) {
25 insert(node.right, value);
26 } else {
27 System.out.println(" Inserted " + value + " to right of "
28 + node.value);
29 node.right = new Node(value);
30 }
31 }
32 }
33 public void traverseInOrder(Node node) {
34 if (node != null) {
35 traverseInOrder(node.left);
36 System.out.print(" " + node.value);
37 traverseInOrder(node.right);
38 }
39 }
40
41 public static void main(String args[])
42 {
43 Tree tree = new Tree();
44 Node root = new Node(5);
45 System.out.println("Binary Tree Example");
46 System.out.println("Building tree with root value " + root.value);
47 tree.insert(root, 2);
48 tree.insert(root, 4);
49 tree.insert(root, 8);
50 tree.insert(root, 6);
51 tree.insert(root, 7);
52 tree.insert(root, 3);
53 tree.insert(root, 9);
54 System.out.println("Traversing tree in order");
55 tree.traverseLevelOrder();
56
57 }
58}
59
60
1package MyPackage;
2
3public class Tree {
4 static class Node {
5 int value;
6 Node left, right;
7
8 Node(int value){
9 this.value = value;
10 left = null;
11 right = null;
12 }
13 }
14
15 public void insert(Node node, int value) {
16 if (value < node.value) { if (node.left != null) { insert(node.left, value); } else { System.out.println(" Inserted " + value + " to left of " + node.value); node.left = new Node(value); } } else if (value > node.value) {
17 if (node.right != null) {
18 insert(node.right, value);
19 } else {
20 System.out.println(" Inserted " + value + " to right of "
21 + node.value);
22 node.right = new Node(value);
23 }
24 }
25 }
26 public void traverseInOrder(Node node) {
27 if (node != null) {
28 traverseInOrder(node.left);
29 System.out.print(" " + node.value);
30 traverseInOrder(node.right);
31 }
32 }
33
34 public static void main(String args[])
35 {
36 Tree tree = new Tree();
37 Node root = new Node(5);
38 System.out.println("Binary Tree Example");
39 System.out.println("Building tree with root value " + root.value);
40 tree.insert(root, 2);
41 tree.insert(root, 4);
42 tree.insert(root, 8);
43 tree.insert(root, 6);
44 tree.insert(root, 7);
45 tree.insert(root, 3);
46 tree.insert(root, 9);
47 System.out.println("Traversing tree in order");
48 tree.traverseLevelOrder();
49
50 }
51}