Skip to content

Commit cf46536

Browse files
author
Pan
committed
二叉树
1 parent 551df02 commit cf46536

File tree

1 file changed

+59
-18
lines changed

1 file changed

+59
-18
lines changed

group11/252308879/dataStructure/src/main/java/org/apn/coding2017/basic/BinaryTreeNode.java

Lines changed: 59 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,74 @@
33
/**
44
* Created by QiPan on 2017/2/23.
55
*/
6-
public class BinaryTreeNode {
6+
public class BinaryTreeNode<Key extends Comparable<Key>, Value> {
77

8-
private Object data;
9-
private BinaryTreeNode left;
10-
private BinaryTreeNode right;
8+
private Node root;
119

12-
public Object getData() {
13-
return data;
10+
private class Node {
11+
private Key key;
12+
private Value value;
13+
private Node left, right; //指向子树的链接
14+
private int N; // 以该节点为根的子树节点总数
15+
public Node(Key key, Value value, int N) {
16+
this.key = key;
17+
this.value = value;
18+
this.N = N;
19+
}
1420
}
15-
public void setData(Object data) {
16-
this.data = data;
21+
22+
public int size() {
23+
return size(root);
1724
}
18-
public BinaryTreeNode getLeft() {
19-
return left;
25+
26+
private int size(Node x) {
27+
if (x == null) return 0;
28+
else return x.N;
2029
}
21-
public void setLeft(BinaryTreeNode left) {
22-
this.left = left;
30+
31+
public Value get(Key key){
32+
return get(root, key);
2333
}
24-
public BinaryTreeNode getRight() {
25-
return right;
34+
35+
private Value get(Node x, Key key) {
36+
// 如果根节点也是Null 那么返回null
37+
if (x == null){
38+
return null;
39+
}
40+
// 拿需要查询的key 与 根节点的 key 比较
41+
int cmp = key.compareTo(x.key);
42+
if (cmp < 0){ // 如果小于0 那么去左子树上查询,并且递归调用
43+
return get(x.left, key);
44+
}else if (cmp > 0){// 如果大于0 那么去右子树上查询,并且递归调用
45+
return get(x.right, key);
46+
}else {
47+
return x.value;
48+
}
2649
}
27-
public void setRight(BinaryTreeNode right) {
28-
this.right = right;
50+
51+
public void push(Key key, Value value){
52+
// 查询key, 找到则更新它的值,否则就创建
53+
root = put(root, key, value);
2954
}
3055

31-
public BinaryTreeNode insert(Object o){
32-
return null;
56+
private Node put(Node x, Key key, Value value) {
57+
// 如果key 存在于以 x 为根节点的子树中 则更新它的值
58+
// 否则将以key 和 value 为键值对的新节点插入到该子树中
59+
60+
if (x == null){
61+
return new Node(key, value, 1);
62+
}
63+
int cmp = key.compareTo(x.key);
64+
if (cmp < 0 ){
65+
x.left = put(x.left, key, value);
66+
}else if (cmp > 0){
67+
x.right = put(x.right, key, value);
68+
}else { // 存在更新值
69+
x.value = value;
70+
}
71+
// 重新统计节点总数
72+
x.N = size(x.left) + size(x.right) + 1;
73+
return x;
3374
}
3475

3576
}

0 commit comments

Comments
 (0)