1
+ class Node
2
+ {
3
+ int key ;
4
+ Node left , right ;
5
+
6
+ public Node (int item )
7
+ {
8
+ key = item ;
9
+ left = right = null ;
10
+ }
11
+ }
12
+
13
+ class BinaryTree
14
+ {
15
+ Node root ;
16
+
17
+ BinaryTree ()
18
+ {
19
+ root = null ;
20
+ }
21
+ void insert (int key ) {
22
+ root = insertRec (root , key );
23
+ }
24
+ Node insertRec (Node root , int key ) {
25
+ if (root == null ) {
26
+ root = new Node (key );
27
+ return root ;
28
+ }
29
+ if (key < root .key )
30
+ root .left = insertRec (root .left , key );
31
+ else if (key > root .key )
32
+ root .right = insertRec (root .right , key );
33
+ return root ;
34
+ }
35
+ void printPostorder (Node node )
36
+ {
37
+ if (node == null )
38
+ return ;
39
+ printPostorder (node .left );
40
+ printPostorder (node .right );
41
+
42
+ System .out .print (node .key + " " );
43
+ }
44
+ void printInorder (Node node )
45
+ {
46
+ if (node == null )
47
+ return ;
48
+ printInorder (node .left );
49
+ System .out .print (node .key + " " );
50
+ printInorder (node .right );
51
+ }
52
+ void printPreorder (Node node )
53
+ {
54
+ if (node == null )
55
+ return ;
56
+ System .out .print (node .key + " " );
57
+ printPreorder (node .left );
58
+ printPreorder (node .right );
59
+ }
60
+
61
+ // Wrappers over above recursive functions
62
+ void printPostorder () { printPostorder (root ); }
63
+ void printInorder () { printInorder (root ); }
64
+ void printPreorder () { printPreorder (root ); }
65
+
66
+ // Driver method
67
+ public static void main (String [] args )
68
+ {
69
+ BinaryTree tree = new BinaryTree ();
70
+ /*
71
+ tree.root = new Node(1);
72
+ tree.root.left = new Node(2);
73
+ tree.root.right = new Node(3);
74
+ tree.root.left.left = new Node(4);
75
+ tree.root.left.right = new Node(5);
76
+ */
77
+ tree .insert (50 );
78
+ tree .insert (30 );
79
+ tree .insert (20 );
80
+ tree .insert (40 );
81
+ tree .insert (70 );
82
+ tree .insert (60 );
83
+ tree .insert (80 );
84
+ System .out .println ("Preorder traversal of binary tree is " );
85
+ tree .printPreorder ();
86
+
87
+ System .out .println ("\n Inorder traversal of binary tree is " );
88
+ tree .printInorder ();
89
+
90
+ System .out .println ("\n Postorder traversal of binary tree is " );
91
+ tree .printPostorder ();
92
+ }
93
+ }
0 commit comments