zoukankan      html  css  js  c++  java
  • [leetcode] 145. 二叉树的后序遍历

    145. 二叉树的后序遍历

    递归写法

    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            if (root == null) return list;
            dfs(root, list);
            return list;
        }
    
        public void dfs(TreeNode node, List<Integer> ans) {
            if (node.left != null) dfs(node.left, ans);
            if (node.right != null) dfs(node.right, ans);
            ans.add(node.val);
        }
    }
    

    非递归写法
    还是比较难的,要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。如果P不存在左孩子和右孩子,则可以直接访问它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。

    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            if (root == null) return list;
            Stack<TreeNode> stack = new Stack<>();
    
            TreeNode pre = null;
            stack.push(root);
            while (!stack.isEmpty()) {
                root = stack.peek();
                if ((root.left == null && root.right == null) || (pre != null && (pre == root.left || pre == root.right))) {//如果当前结点没有孩子结点或者孩子节点都已被访问过 
                    list.add(root.val);
                    stack.pop();
                    pre = root;
                } else {
                    if (root.right != null) stack.push(root.right);
                    if (root.left != null) stack.push(root.left);
                }
            }
    
            return list;
        }
    }
    
  • 相关阅读:
    xp_cmdshell
    常用SQL语句
    SQL Server Select的递归查询-交叉表
    Sql Server 2005 行转列的实现(横排)
    sql导入导出
    使用正则表达式验证手机号、车牌号
    页面功能:设为首页和加入收藏
    两个文本框同步输入
    最常用的200个JS代码
    .NET 获取时间
  • 原文地址:https://www.cnblogs.com/acbingo/p/9440235.html
Copyright © 2011-2022 走看看