forked from vaibhavnirmal2001/DSA-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse a path in BST using queue
141 lines (85 loc) · 1.51 KB
/
Reverse a path in BST using queue
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import java.util.*;
class GFG
{
static class node
{
int key;
node left, right;
};
static node root = null;
static Queue<Integer> q1;
static int k;
static node newNode(int item)
{
node temp = new node();
temp.key = item;
temp.left = temp.right = null;
return temp;
}
static void inorder(node root)
{
if (root != null)
{
inorder(root.left);
System.out.print(root.key + " ");
inorder(root.right);
}
}
static void reversePath(node node)
{
if (node == null)
return;
if ((node).key == k)
{
q1.add((node).key);
(node).key = q1.peek();
q1.remove();
return;
}
else if (k < (node).key)
{
q1.add((node).key);
reversePath((node).left);
(node).key = q1.peek();
q1.remove();
}
else if (k > (node).key)
{
q1.add((node).key);
reversePath((node).right);
(node).key = q1.peek();
q1.remove();
}
return;
}
static node insert(node node, int key)
{
if (node == null)
return newNode(key);
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
return node;
}
public static void main(String[] args)
{
q1 = new LinkedList<>();
k = 80;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
System.out.print("Before Reverse :"
+ "\n");
inorder(root);
System.out.print("\n");
reversePath(root);
System.out.print("After Reverse :"
+ "\n");
inorder(root);
}
}