-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarytree.java
More file actions
115 lines (94 loc) · 2.35 KB
/
Binarytree.java
File metadata and controls
115 lines (94 loc) · 2.35 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.sai;
public class Binarytree {
Node root;
public void addNode(int key, String name) {
Node newNode = new Node(key, name);
if (root == null) {
root = newNode;
} else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (key < focusNode.key) {
focusNode = focusNode.leftchild;
if (focusNode == null) {
parent.leftchild = newNode;
return;
}
} else {
focusNode = focusNode.rightchild;
if (focusNode == null) {
parent.rightchild = newNode;
return;
}
}
}
}
}
public void inOrderTraversalTree(Node focusNode) {
if (focusNode != null) {
inOrderTraversalTree(focusNode.leftchild);
System.out.println(focusNode);
inOrderTraversalTree(focusNode.rightchild);
}
}
public void preOrderTraversalTree(Node focusNode) {
if (focusNode != null) {
System.out.println(focusNode);
inOrderTraversalTree(focusNode.leftchild);
inOrderTraversalTree(focusNode.rightchild);
}
}
public void postOrderTraversalTree(Node focusNode) {
if (focusNode != null) {
inOrderTraversalTree(focusNode.leftchild);
inOrderTraversalTree(focusNode.rightchild);
System.out.println(focusNode);
}
}
public Node findNode(int key) {
Node focusNode = root;
while (focusNode.key != key) {
if (key < focusNode.key) {
focusNode = focusNode.leftchild;
} else {
focusNode = focusNode.rightchild;
}
if (focusNode == null) {
return null;
}
}
return focusNode;
}
public static void main(String[] args) {
Binarytree theTree = new Binarytree();
theTree.addNode(10, "sai");
theTree.addNode(40, "rakesh");
theTree.addNode(30, "ravi");
theTree.addNode(50, "abhinav");
theTree.addNode(20, "raghu");
theTree.addNode(60, "vinay");
System.out.println("Inorder traversel is:");
theTree.inOrderTraversalTree(theTree.root);
System.out.println("Search for 30");
System.out.println(theTree.findNode(30));
System.out.println("Preorder traversel is:");
theTree.preOrderTraversalTree(theTree.root);
System.out.println("Postorder traversel is:");
theTree.postOrderTraversalTree(theTree.root);
}
}
class Node {
int key;
String name;
Node leftchild;
Node rightchild;
Node(int key, String name) {
this.key = key;
this.name = name;
}
public String toString() {
return key + " name is " + name;
}
}