File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .Scanner ;
2+
3+ public class Tree {
4+
5+ static Scanner sc = null ;
6+ public static void main (String [] args ) {
7+ sc = new Scanner (System .in );
8+
9+ Node root = createTree ();
10+ inOrder (root );
11+ System .out .println ();
12+ preOrder (root );
13+ System .out .println ();
14+ postOrder (root );
15+ System .out .println ();
16+ }
17+
18+ static Node createTree () {
19+
20+ Node root = null ;
21+ System .out .println ("Enter data: " );
22+ int data = sc .nextInt ();
23+
24+ if (data == -1 ) return null ;
25+
26+ root = new Node (data );
27+
28+ System .out .println ("Enter left for " + data );
29+ root .left = createTree ();
30+
31+ System .out .println ("Enter right for " + data );
32+ root .right = createTree ();
33+
34+ return root ;
35+ }
36+
37+ static void inOrder (Node root ) {
38+ if (root == null ) return ;
39+
40+ inOrder (root .left );
41+ System .out .print (root .data +" " );
42+ inOrder (root .right );
43+ }
44+
45+ static void preOrder (Node root ) {
46+ if (root == null ) return ;
47+ System .out .print (root .data +" " );
48+ preOrder (root .left );
49+ preOrder (root .right );
50+ }
51+
52+ static void postOrder (Node root ) {
53+ if (root == null ) return ;
54+
55+ postOrder (root .left );
56+ postOrder (root .right );
57+ System .out .print (root .data +" " );
58+ }
59+ }
60+
61+ class Node {
62+ Node left , right ;
63+ int data ;
64+
65+ public Node (int data ) {
66+ this .data = data ;
67+ }
68+ }
You can’t perform that action at this time.
0 commit comments