-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBiTree.java
More file actions
83 lines (72 loc) · 2.16 KB
/
Copy pathBiTree.java
File metadata and controls
83 lines (72 loc) · 2.16 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
package DataStructure;
import java.util.Stack;
public class BiTree {//这个代码是错的,目前能力不足,无法纠正 2022.3.24
public class Node {
private Object value;
private Node left;
private Node right;
public Node(){}
public Node(Object value,Node left,Node right) {
this.value = value;
this.left = left;
this.right = right;
}
public Node(Object value){
this.value = value;
}
public Object getValue() {
return value;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
public void setValue(Object value) {
this.value = value;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
}
private Node root;
private int index = 0;
public BiTree(String str) {//先序遍历建树 直接写在构造方法里,和C++不一样
char c = str.charAt(index++);
if(c != '#'){
root = new Node(c);
root.left = new BiTree(str).root;
root.right = new BiTree(str).root;
} else root = null;//构造函数哪有返回值
}
public void preRootTraverse(){
Node T = root;
if(T != null) {
Stack<Node> stack = new Stack<Node>();
stack.push(T);
while(!stack.isEmpty()){
Node temp = stack.pop();
System.out.print(temp.value);
while(T != null) {
if(T.left != null){
System.out.println(T.left.value);
}
if(T.right != null){
stack.push(T.right);
}
T = T.left;
}
}
}
}
public static void main(String[] args) {
String str = "AB##CD###";
BiTree t = new BiTree(str);
System.out.println("先序遍历:");
t.preRootTraverse();
}
}