//前序遍历
public static void preOrder(Node node) {
if (node == null) {
return;
}
System.out.print(node.value);
preOrder(node.left);
preOrder(node.right);
}
//中序遍历
public static void inOrder(Node node) {
if (node == null) {
return;
}
inOrder(node.left);
System.out.print(node.value);
inOrder(node.right);
}
//后序遍历
public static void postOrder(Node node) {
if (node == null) {
return;
}
postOrder(node.left);
postOrder(node.right);
System.out.print(node.value);
}
/**
* 非递归实现
*/
//前序遍历
public static void preOrder02(Node node) {
Stack<Node> stack = new Stack<>();
while (node != null || !stack.isEmpty()) {
while (node != null) {
System.out.print(node.value);
stack.push(node);
node = node.left;
}
node = stack.pop().right;
}
}
//中序遍历
public static void inOrder02(Node node) {
Stack<Node> stack = new Stack<>();
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
System.out.print(node.value);
node = node.right;
}
}
//后序遍历
public static void postOrder2(Node node) {
Stack<Node> stack = new Stack<Node>();
Stack<Integer> tag = new Stack<Integer>();
while (node != null || !stack.isEmpty()) {
if (node != null) {
stack.push(node);
tag.push(1); //第一次访问
node = node.left;
} else {
if (tag.peek() == 2) {
System.out.print(stack.pop().value);
tag.pop();
} else {
tag.pop();
tag.push(2); //第二次访问
node = stack.peek().right;
}
}
}
}
测试用例
//测试用例
public static void test(Node node) {
System.out.print("递归_前序排序:");
preOrder(node);
System.out.println();
System.out.print("前序排序:");
preOrder02(node);
System.out.println();
System.out.print("递归_中序遍历:");
inOrder(node);
System.out.println();
System.out.print("中序遍历:");
inOrder02(node);
System.out.println();
System.out.print("递归_后序排序:");
postOrder(node);
System.out.println();
System.out.print("后序排序:");
postOrder2(node);
System.out.println();
}
public static void main(String[] args) {
BST<Integer, Integer> bst = new BST<>();
bst.put(3, 3);
bst.put(2, 2);
bst.put(4, 4);
TreeOrder.test(bst.root);
}
输出
递归_前序排序:324
前序排序:324
递归_中序遍历:234
中序遍历:234
递归_后序排序:243
后序排序:243
原文:https://www.cnblogs.com/aiguozou/p/11440207.html