-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.java
More file actions
99 lines (86 loc) · 2.26 KB
/
Copy pathBST.java
File metadata and controls
99 lines (86 loc) · 2.26 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
package dummy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class BST {
public BST() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
BSTNode root=null;
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
for(int i=0; i<n; i++) {
root= insertBSTNode(root, sc.nextInt());
}
root= deleteBSTNode(root, sc.nextInt());
printBST(root);
}
public static void printBST(BSTNode root) {
if(root==null) return;
System.out.println(root.key);
printBST(root.left);
printBST(root.right);
}
static BSTNode insertBSTNode(BSTNode root, int key) {
//System.out.println("hello ");
if(root==null) {
return new BSTNode(key);
}
else if(key<root.key) {
root.left= insertBSTNode(root.left, key);
}
else {
root.right= insertBSTNode(root.right, key);
}
return root;
}
static BSTNode deleteBSTNode(BSTNode root, int key)
{
if(root==null) return null;
if(root.key==key) {
if(root.left==null && root.right==null) {
return null;
}
else if(root.left==null) {
return root.right;
}
else if(root.right==null) {
return root.left;
}
else {
BSTNode newBSTNode=root;
BSTNode prev=root;
root=root.right;
if(root.left==null) {
prev.right=root.right;
} else {
while(root.left!=null) {
prev=root;
root=root.left;
}
prev.left=root.right;
}
newBSTNode.key=root.key;
return newBSTNode;
}
}
else if(root.key>key) {
root.left= deleteBSTNode(root.left, key);
} else {
root.right= deleteBSTNode(root.right, key);
}
return root;
}
}
class BSTNode
{
int key;
BSTNode left, right;
BSTNode(int item)
{
key = item;
left = right = null;
}
}