-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayTree.java
104 lines (95 loc) · 2.28 KB
/
ArrayTree.java
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
package week_8.wangwei.ArrayTree;
/**
* 数组存储树
* @author yohoyes
*/
public class ArrayTree {
private ArrayTreeNode[] list = null;
private int length;
public ArrayTree(int length){
this.length = length;
list = new ArrayTreeNode[length+1];
}
/**
* 获取index元素的左子节点
* @return
*/
public ArrayTreeNode getChildLeft(ArrayTreeNode node){
for(int i=1; i<length; i++){
if (list[i].getValue() == node.getValue()){
if(i*2<=length){
return list[i*2];
}
}
}
return null;
}
/**
* 获取index元素的右子节点
* @return
*/
public ArrayTreeNode getChildRight(ArrayTreeNode node){
for(int i=1; i<length; i++){
if (list[i].getValue() == node.getValue()){
if(i*2+1<=length){
return list[i*2+1];
}
}
}
return null;
}
/**
* 获取父节点
* @param node
* @return
*/
public ArrayTreeNode getParent(ArrayTreeNode node){
for(int i=1; i<length; i++){
if (list[i].getValue() == node.getValue()){
int index;
if(i%2==0){
index = i/2;
}else {
index = (i-1)/2;
}
return list[index];
}
}
return null;
}
/**
* 添加左子节点
* @param parent
* @param child
*/
public void addChildLeft(ArrayTreeNode parent, ArrayTreeNode child){
int index = getIndex(parent);
if(index!=-1){
list[index*2] = child;
}
}
/**
* 添加右子节点
* @param parent
* @param child
*/
public void addChildRight(ArrayTreeNode parent, ArrayTreeNode child){
int index = getIndex(parent);
if(index!=-1){
list[index*2+1] = child;
}
}
/**
* 获取某节点的下标
* @param node
* @return
*/
public int getIndex(ArrayTreeNode node){
for(int i=1;i<length+1;i++){
if(node.getValue() == list[i].getValue()) {
return i;
}
}
return -1;
}
}