-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeNode.java
More file actions
82 lines (67 loc) · 1.77 KB
/
Copy pathTreeNode.java
File metadata and controls
82 lines (67 loc) · 1.77 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
package a.binarytree;
public class TreeNode {
private int data;
private TreeNode leftChild;
private TreeNode rightChild;
public void insert(int value) {
if (value == data) {
return;
}
if (value < data) {
if (leftChild == null) {
leftChild = new TreeNode(value);
}
else {
leftChild.insert(value);
}
}
else {
if (rightChild == null) {
rightChild = new TreeNode(value);
}
else {
rightChild.insert(value);
}
}
}
public void traverseInOrder() {
if (leftChild != null) {
leftChild.traverseInOrder();
}
System.out.print(data + ", ");
if (rightChild != null) {
rightChild.traverseInOrder();
}
}
public TreeNode(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public TreeNode getLeftChild() {
return leftChild;
}
public void setLeftChild(TreeNode leftChild) {
this.leftChild = leftChild;
}
public TreeNode getRightChild() {
return rightChild;
}
public void setRightChild(TreeNode rightChild) {
this.rightChild = rightChild;
}
public TreeNode search(TreeNode root,int key){
if(root==null || root.getData()==key){
System.out.println("Element Found" + root.toString());
return root;
}
if (root.getData() > key)
return search(root.getLeftChild(), key);
// val is less than root's key
return search(root.getRightChild(), key);
}
}