二叉树的后序非递归遍历(巧妙思想)

大家都知道二叉树的前序非递归遍历非常好写:

//二叉树的结构
public class TreeNode {
    TreeNode left;
    TreeNode right;
    int val;

    TreeNode(int val) {
        this.val = val;
        left = right = null;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

首先判断根是否为空,将根节点入栈

1.若栈为空,则退出循环 
2.将栈顶元素弹出,访问弹出的节点 
3.若弹出的节点的右孩子不为空则将右孩子入栈 
4.若弹出的节点的左孩子不为空则将左孩子入栈 
5.返回1

void preOrder(){
    Stack<TreeNode> stack = new Stack<TreeNode>();
    if (root != null) {
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.pop();
            visit(root);
            if (root.right != null) {
                stack.push(root.right);
            }
            if (root.left != null) {
                stack.push(root.left);
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

而二叉树的后序非递归遍历就比较难写,因为涉及到判断节点的访问状态…

现在有个很巧妙的方法:

前序:根->左->右 
后序:左->右->根

那么可以把后序当作:根->右->左,然后再反转一下即可。

ArrayList<Integer> postOrder(TreeNode root) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    if (root != null) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        //反转
        Collections.reverse(list);
    }
    return list;
}
全部评论

相关推荐

头像
2025-12-27 13:01
三峡大学 C++
点赞 评论 收藏
分享
02-01 12:05
复旦大学 Java
腾讯的提前批大概率应该是没有笔试的,但是这个时候有相当部分的同学简历估计都没有准备好,没准备好的同学也不用急,大部分都是3月之后开,这个时候开的绝大多数都是神仙打架,问的东西也比较难,打算投递的同学也多看下计算机网络和操作系统,腾讯对这部分的知识问的比较多。另外多刷下牛客的热门题库,刷题注意刷ACM模式,和牛客的周赛题,腾讯有的部门会从这里面出原题。我是@程序员花海关注我,带你了解更多校招资讯!
程序员花海:还没有来得及准备的同学可以看下学习路线:https://www.nowcoder.com/discuss/824693499982315520?sourceSSR=users算法题:https://www.nowcoder.com/feed/main/detail/20e7a999fa04485b88340a274411ca0d?sourceSSR=users八股文:https://www.nowcoder.com/discuss/833102362771251200?sourceSSR=users简历书写方式:https://www.nowcoder.com/discuss/839907820706205696?sourceSSR=users都是以前在牛客发的文章~
软开人,秋招你打算投哪些...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务