-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBT_Create__DFS.java
More file actions
100 lines (85 loc) · 2.32 KB
/
Copy pathBT_Create__DFS.java
File metadata and controls
100 lines (85 loc) · 2.32 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package Algorithms;
import java.util.Scanner;
/*
Binary Tree
4
/ \
/ \
2 7
/ \ / \
/ \ / \
1 3 6 9
*/
public class BT_Create__DFS {
static Scanner input = null;
public static void main(String[] args) {
try
{ input = new Scanner(System.in);
NODE root = CreateTree();
System.out.print("\n\n\nInorder :");
inOrder(root);
System.out.print("\npreOrder :");
preOrder(root);
System.out.print("\npostOrder :");
postOrder(root);
System.out.println("\nInvert Order : ");
invertTree( root);}
catch(Exception e){
System.out.println("Catch");
}
}
static NODE CreateTree() {
NODE newNode = null; // newNode Means Root of subtree
System.out.print("Data : ");
int data = input.nextInt();
if (data == -1) {
return null;
}
newNode = new NODE(data);
System.out.println("Left of root :" + data);
newNode.left = CreateTree();
System.out.println("Right of root :" + data);
newNode.right = CreateTree();
return newNode;
}
static void inOrder(NODE root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
static void preOrder(NODE root) {
if (root == null) {
return;
}
System.out.print(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
static void postOrder(NODE root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data + " ");
}
static NODE invertTree(NODE root) {
if(root==null)
return null;
NODE temp=root.left;
System.out.print(root.data+" ");
root.left=invertTree(root.right);
root.right=invertTree(temp);
return null;
}
}
class NODE {
NODE left, right;
int data;
public NODE(int data) {
this.data = data;
}
}