-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.java
More file actions
143 lines (135 loc) · 3.43 KB
/
Tree.java
File metadata and controls
143 lines (135 loc) · 3.43 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
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
141
142
143
import java.util.Stack;
public class Tree {
class Node {
public int iData;
public double dData;
public Node leftNode;
public Node rightNode;
}
Node root;
public Node find(int key){
Node n = root;
while(n != null && n.iData != key){
if(n.iData > key){
n = n.leftNode;
}
else{
n = n.rightNode;
}
}
return n;
}
public void insert(int id, double dd){
Node t = new Node();
t.iData = id;
t.dData = dd;
Node n = root;
while(n != null){
if(n.iData > id){
if(n.leftNode == null){
n.leftNode = t;
break;
}
else{
n = n.leftNode;
}
}
else{
if(n.rightNode == null){
n.rightNode = t;
break;
}
else{
n = n.rightNode;
}
}
}
if(root == null){
root = t;
}
}
public boolean delete(int key){
Node header = new Node();
header.leftNode = root;
Node curr = root, parent = header;
while(curr != null && curr.iData != key){
parent = curr;
if(curr.iData > key){
curr = curr.leftNode;
}
else{
curr = curr.rightNode;
}
}
if(curr == null){
return false;
}
Node next = curr.rightNode, nextParent = curr;
while(next != null && next.leftNode != null){
nextParent = next;
next = next.leftNode;
}
if (next == null){
if(curr == parent.leftNode){
parent.leftNode = curr.leftNode;
}
else{
parent.rightNode = curr.leftNode;
}
return true;
}
else{
curr.iData = next.iData;
curr.dData = next.dData;
nextParent.leftNode = null;
return true;
}
}
class pair{
public boolean is = true;
public int leftLeast;
public int leftMost;
public int rightMost;
public int rightLeast;
}
public boolean isBST(Tree t){
return isBSTHelper(t.root);
}
private boolean isBSTHelper(Node n){
Stack<Node> stack = new Stack<>();
int prev = Integer.MIN_VALUE;
while(true){
if(n != null){
stack.add(n);
n = n.leftNode;
}
else{
if(stack.isEmpty()){
break;
}
n = stack.pop();
if(n.iData <= prev){
return false;
}
prev = n.iData;
n = n.rightNode;
}
}
return true;
}
public static void main(String[] args) {
Tree t = new Tree();
t.insert(1,1.1);
t.insert(3,3.3);
t.insert(5,5.5);
t.insert(2,2.2);
t.insert(4,4.4);
t.insert(6,6.6);
System.out.println(t.find(1).dData);
System.out.println(t.find(5).dData);
System.out.println(t.find(6).dData);
t.delete(6);
t.delete(3);
t.delete(1);
}
}