-
Notifications
You must be signed in to change notification settings - Fork 2
/
GetParentNodeOfNodeInBST.java
106 lines (70 loc) · 1.66 KB
/
GetParentNodeOfNodeInBST.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
95
96
97
98
99
100
101
102
103
104
105
106
public class GetParentNodeOfNodeInBST {
class Node {
int data;
Node left;
Node right;
}
public Node insert(Node node, int data) {
if (node == null) {
return createNewNode(data);
}
if (data < node.data) {
node.left = insert(node.left, data);
}
if (data > node.data) {
node.right = insert(node.right, data);
}
return node;
}
public Node createNewNode(int data) {
Node node = new Node();
node.data = data;
node.left = null;
node.right = null;
return node;
}
public void inOrder(Node root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
public Node getParentNode(Node root, int data) {
if (root == null) {
return null;
}
Node parent = null;
while (root.data != data) {
if (data < root.data) {
parent = root;
root = root.left;
}
if (data > root.data) {
parent = root;
root = root.right;
}
if (data == root.data) {
break;
}
}
return parent;
}
public static void main(String[] args) {
GetParentNodeOfNodeInBST opr = new GetParentNodeOfNodeInBST();
Node root = null;
root = opr.insert(root, 8);
root = opr.insert(root, 3);
root = opr.insert(root, 6);
root = opr.insert(root, 10);
root = opr.insert(root, 4);
root = opr.insert(root, 7);
root = opr.insert(root, 1);
root = opr.insert(root, 14);
root = opr.insert(root, 13);
Node parent = opr.getParentNode(root, 3);
System.out.println("Parent node : " + parent.data);
opr.inOrder(root);
}
}