-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathImplementation.java
94 lines (68 loc) · 1.75 KB
/
Implementation.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
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
package tree;
import java.util.Scanner;
public class Trees {
static Scanner sc = null ;
public static void main(String[] args) {
sc = new Scanner (System.in);
System.out.println("Enter root : ");
Node root = createTree() ;
// inOrder(root);
// System.out.println();
// preOrder(root);
// System.out.println();
// postOrder(root);
// getsize(root);
}
static Node createTree() {
Node root = null ;
int data = sc.nextInt();
if(data == -1) return null;
root = new Node (data);
System.out.println("Enter left for " + data);
root.left = createTree();
System.out.println("Enter right for " + data);
root.right = createTree();
return root ;
}
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 int getSize(Node root) {
if(root == null) return 0 ;
return 1 + getSize(root.left) + getSize(root.right) ;
}
static void display(Node node) {
if(node == null) return;
String str ="";
if(node.left == null) str += ".";
else str += node.left.data;
str += " => " + node.data + " <= ";
if(node.right == null) str+= ".";
else str += node.right.data;
System.out.println(str);
display(node.left);
display(node.right);
}
}
class Node {
Node left , right ;
int data ;
public Node(int data) {
this.data = data ;
}
}