forked from kexun/sort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoopTreeByStack.java
124 lines (96 loc) · 2.09 KB
/
LoopTreeByStack.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package com.demo;
import java.util.Stack;
/**
* 非递归的方式遍历二叉树,先序,中序,后续。利用栈。
* @author kexun
*
*/
public class LoopTreeByStack {
public static void main(String[] args) {
Tree head = new Tree(1);
Tree h2 = new Tree(2);
Tree h3 = new Tree(3);
Tree h4 = new Tree(4);
Tree h5 = new Tree(5);
Tree h6 = new Tree(6);
Tree h7 = new Tree(7);
Tree h8 = new Tree(8);
Tree h9 = new Tree(9);
Tree h10 = new Tree(10);
head.left = h2;
head.right = h3;
h2.left = h4;
h2.right = h5;
h4.left = h6;
h5.right = h7;
h3.left = h8;
h3.right = h9;
h9.right = h10;
LoopTreeByStack l = new LoopTreeByStack();
// l.preOrder(head);
// l.inOrder(head);
l.afterOrder(head);
}
/**
* 先序
* @param head
*/
public void preOrder(Tree head) {
Stack<Tree> stack = new Stack<Tree>();
stack.push(head);
while (!stack.isEmpty()) {
Tree tree = stack.pop();
if (tree.right != null) {
stack.push(tree.right);
}
if (tree.left != null) {
stack.push(tree.left);
}
System.out.println(tree.data);
}
}
/**
* 中序
* @param head
*/
public void inOrder(Tree head) {
Stack<Tree> stack = new Stack<Tree>();
stack.push(head);
while (!stack.isEmpty()) {
Tree tree = stack.pop();
if (tree.left == null && tree.right == null) {
System.out.println(tree.data);
} else {
if (tree.right != null) {
stack.push(tree.right);
tree.right = null;
}
stack.push(tree);
if (tree.left != null) {
stack.push(tree.left);
tree.left = null;
}
}
}
}
public void afterOrder(Tree head) {
Stack<Tree> stack = new Stack<Tree>();
stack.push(head);
while (!stack.isEmpty()) {
Tree tree = stack.pop();
if (tree.left == null && tree.right == null) {
System.out.println(tree.data);
} else {
stack.push(tree);
if (tree.right != null) {
stack.push(tree.right);
tree.right = null;
}
if (tree.left != null) {
stack.push(tree.left);
tree.left = null;
}
}
}
}
}