码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 145. 二叉树的后序遍历

时间:2020-10-27 11:40:04      阅读:20      评论:0      收藏:0      [点我收藏+]

标签:lis   注意   return   结果   post   empty   pop   collect   integer   

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        //一般解法,前序遍历后,翻转下结果集,注意下 与前序遍历的进栈顺序不一样
        //(前序) 根左右 --> 变为 根右左 --> 翻转 左右根 (后续)
        //定义一一个栈
        Stack<TreeNode> stack = new Stack<>();
        //定义返回的结果集
        List<Integer> res = new LinkedList();
 
        if(root == null) return res;
        //根节点入栈
        stack.push(root);
         
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            res.add(node.val);
            if(node.left != null) stack.push(node.left);
            if(node.right != null) stack.push(node.right);    
        }
        Collections.reverse(res);
        return res;
    }
}

 

LeetCode 145. 二叉树的后序遍历

标签:lis   注意   return   结果   post   empty   pop   collect   integer   

原文地址:https://www.cnblogs.com/peanut-zh/p/13881778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!