forked from destiny1020/algorithm_playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBT.java
More file actions
123 lines (93 loc) · 2.14 KB
/
BT.java
File metadata and controls
123 lines (93 loc) · 2.14 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
package chap3;
/**
* 就是普通的二叉树,非搜索二叉树(BST)
* @author Destiny
*
* @param <Key>
* @param <Value>
*/
public class BT<Key, Value> {
private Node<Key, Value> root;
private int sz;
public BT(Node<Key, Value> root) {
this.root = root;
sz = root.N;
}
/**
*
* @param root
* @param left
* @param right
*/
public BT(Node<Key, Value> root, Node<Key, Value> left, Node<Key, Value> right) {
}
public void setRoot(Node<Key, Value> root) {
this.root = root;
}
public Node<Key, Value> getRoot() {
return root;
}
/**
* 检查BT是否为空,如果root为空,则该BT为空
* @return
*/
public boolean isEmpty() {
return (null == root);
}
/**
* 将bt作为当前bt的左子树, 并返回之前的左子树
* @param bt
* @return
*/
public BT<Key, Value> replaceLeft(BT<Key, Value> bt) {
BT<Key, Value> originLeft = new BT<Key, Value>(root.left);
sz -= originLeft.sz;
root.left = bt.getRoot();
sz += bt.sz;
return originLeft;
}
/**
* 将bt作为当前bt的右子树, 并返回之前的右子树
* @param bt
* @return
*/
public BT<Key, Value> replaceRight(BT<Key, Value> bt) {
BT<Key, Value> originRight = new BT<Key, Value>(root.right);
sz -= originRight.sz;
root.right = bt.getRoot();
sz += bt.sz;
return originRight;
}
/**
* 将右子树替换成一个单节点
* @param bt
* @return
*/
public BT<Key, Value> replaceRight(Node<Key, Value> node) {
// 需要检查该节点的左右子树均为空
if(null != node.left || null != node.right) {
return null;
}
BT<Key, Value> originRight = new BT<Key, Value>(root.right);
sz -= originRight.sz;
root.right = node;
sz += 1;
return originRight;
}
/**
* 将左子树替换成一个单节点
* @param bt
* @return
*/
public BT<Key, Value> replaceLeft(Node<Key, Value> node) {
// 需要检查该节点的左右子树均为空
if(null != node.left || null != node.right) {
return null;
}
BT<Key, Value> originLeft = new BT<Key, Value>(root.left);
sz -= originLeft.sz;
root.left = node;
sz += 1;
return originLeft;
}
}