-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSTree.java
98 lines (87 loc) · 2.23 KB
/
BSTree.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
package java_uestc;
//二叉排序树
import java.util.ArrayList;
public class BSTree {
public int nodenum;
public TreeNode head ;
public ArrayList<Integer> buff; //用于遍历时存储所有树节点的值
private class TreeNode{
public TreeNode lchild;
public TreeNode rchild;
public int value;
public TreeNode(){
this.value = -1;
}
}
public BSTree(){
this.head = new TreeNode();
this.head.lchild = new TreeNode();
this.head.rchild = new TreeNode();
buff = new ArrayList<Integer>();
}
public void add(TreeNode node,int x){
if(this.head.value == -1){
this.head.value = x;
}
else if(node.value == -1){
node.value = x;
node.lchild = new TreeNode();
node.rchild = new TreeNode();
}
else{
if(x < node.value){
add(node.lchild, x);
}else{
add(node.rchild, x);
}
}
}
public void merge(TreeNode head){
this.buff.clear();
this.print(head, 0, true);
for(int i=0 ; i<buff.size() ; i++){
add(this.head, buff.get(i));
}
}
/*
* 按从大到小顺序遍历
* node:要遍历树的头结点
* thr:门限值,不小于门限值的才会被输出
* isStore:若为true,则遍历时将遍历的结果存入到buffer
* 若为false,则遍历时在控制台输出结果
*/
public void print(TreeNode node,int thr,boolean isStore){
if(node.rchild.value != -1){
this.print(node.rchild,thr,isStore);
}
if(node.value >= thr){
if(isStore) this.buff.add(node.value);
else System.out.print(node.value+" ");
}
if(node.lchild.value != -1){
this.print(node.lchild,thr,isStore);
}
}
public static void main(String[] args) {
BSTree mytree = new BSTree();
mytree.add(mytree.head, 2);
mytree.add(mytree.head, 1);
mytree.add(mytree.head, 5);
mytree.add(mytree.head, 6);
mytree.add(mytree.head, 9);
mytree.add(mytree.head, 3);
mytree.add(mytree.head, 4);
mytree.print(mytree.head,0,false);
System.out.println("");
BSTree youtree = new BSTree();
youtree.add(youtree.head, 7);
youtree.add(youtree.head, 8);
youtree.add(youtree.head, 0);
youtree.add(youtree.head, 4);
youtree.add(youtree.head, 10);
youtree.print(youtree.head, 0, false);
System.out.println("");
mytree.merge(youtree.head);
mytree.print(mytree.head, 0, false);
}
}