TreeNode node = stack.pop();
// 打印节点值
System.out.print(node.value + " ");
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
}
后序遍历递归实现:先序遍历反过来,就不赘述了。
public static void postOrderByRecursion(TreeNode root) {
postOrderByRecursion(root.left);
postOrderByRecursion(root.right);
System.out.println(root.value);
}
后序遍历非递归实现:后序遍历就是先序遍历反过来,所以需要两个栈,多出来的栈用来反向输出。
public static void postOrder(TreeNode root) {
if (root == null) {
return;
}
Stack s1 = new Stack<>();
Stack s2 = new Stack<>();
s1.push(root);
while (!s1.empty()) {
TreeNode node = s1.pop();
s2.push(node);
if (node.left != null) {
s1.push(node.left);
}
if (node.ri 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 ght != null) {
s1.push(node.right);
}
}
while (!s2.empty()) {
System.out.println(s2.pop().value);
}
}
中序遍历
中序遍历先遍历左子树,再遍历根节点,再遍历右子树。
递归遍历:
public static void inOrderByRecursion(TreeNode root) {
if (root == null) {
return;
}
inOrderByRecursion(root.left);
// 打印节点值
System.out.println(root.value);
inOrderByRecursion(root.right);
}
非递归遍历:
-
将二叉树的左侧“边”从上到下依次压入栈中。
-
从栈中弹出节点
-
对以弹出节点的右子节点为根节点的子树,重复步骤1。
-
重复2、3步骤,直到栈为空。
public static void inOrder(TreeNode root) {
if (root == null) {
return;
}
Stack stack = new Stack<>();
TreeNode cur = root;
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
while (!stack.empty()) {
TreeNode node = stack.pop();
System.out.println(node.value);
cur = node.right;
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
}
}