LeetCode-145. 二叉树的后序遍历(相关话题:栈)

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

Java代码:

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        if (null != root) {
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);

            while (!stack.isEmpty()) {
                TreeNode tmp;
                if (null == stack.peek().left && null == stack.peek().right) {
                    tmp = stack.pop();
                    result.add(tmp.val);
                } else {
                    tmp = stack.peek();
                    if (null != tmp.right) {
                        stack.push(tmp.right);
                        tmp.right = null;
                    }
                    if (null != tmp.left) {
                        stack.push(tmp.left);
                        tmp.left = null;
                    }
                }
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38823568/article/details/89373621