二叉树的遍历
先序遍历二叉树
LinkedList<Integer> stack = new LinkedList<>();
BinaryTree<String> binaryTree = new BinaryTree<>(
new String[]{"A", "B", "C", "D", "E", "F", "G"});
System.out.println(binaryTree);
int root = binaryTree.root();
while (root > -1 || !stack.isEmpty()) {
//先访问左子树,并且入栈
while (root > -1) {
String value = binaryTree.get(root);
print(value);
stack.push(root);
root = binaryTree.left(root);
}
//处理右子树
if (!stack.isEmpty()) {
root = stack.pop();
root = binaryTree.right(root);
}
}
A
BC
DEFG
ABDECFG
中序遍历二叉树
LinkedList<Integer> stack = new LinkedList<>();
BinaryTree<String> binaryTree = new BinaryTree<>(
new String[]{"A", "B", "C", "D", "E", "F", "G"});
System.out.println(binaryTree);
int root = binaryTree.root();
while (root > -1 || !stack.isEmpty()) {
//先左子树入栈
while (root > -1) {
stack.push(root);
root = binaryTree.left(root);
}
//访问,处理右子树
if (!stack.isEmpty()) {
root = stack.pop();
String value = binaryTree.get(root);
print(value);
root = binaryTree.right(root);
}
}
A
BC
DEFG
DBEAFCG
后序遍历二叉树
LinkedList<Integer> stack = new LinkedList<>();
BinaryTree<String> binaryTree = new BinaryTree<>(
new String[]{"A", "B", "C", "D", "E", "F", "G"});
System.out.println(binaryTree);
int root = binaryTree.root();
int lastAccess = Integer.MAX_VALUE;
while (root > -1 || !stack.isEmpty()) {
//先左子树入栈
while (root > -1) {
stack.push(root);
root = binaryTree.left(root);
}
root = stack.peek();
int right = binaryTree.right(root);
//没有右子树访问,出栈
if (right == -1 || right == lastAccess) {
lastAccess = root;
String value = binaryTree.get(root);
print(value);
stack.pop();
root = -1;
} else {
root = right;
}
}
A
BC
DEFG
DEBFGCA
引用