leetcode 145. Binary Tree Postorder Traversal-后续遍历|递归|非递归

原题链接:145. Binary Tree Postorder Traversal

【思路-Java、Python】-非递归实现

以[1,2,3,4,5,null,6]为例,需要用到一个栈,具体执行过程如下图所示:


stack 取出的节点值是从 res 的头部插入的,这点与二叉树的前序遍历、中序遍历存在不同:

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        List<Integer> res = new ArrayList<Integer>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode temp = stack.pop();
            if (temp != null) {
                res.add(0, temp.val);
                stack.add(temp.left);
                stack.add(temp.right);
            }
        }
        return res;
    }
}
67 / 67  test cases passed. Runtime: 2 ms  Your runtime beats 7.50% of javasubmissions.

class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        stack = []
        stack.append(root)
        res = []
        while stack :
            temp = stack.pop()
            if temp :
                res.append(temp.val)
                stack.append(temp.left)
                stack.append(temp.right)
        return res[::-1]
67 / 67  test cases passed. Runtime: 40 ms  Your runtime beats 67.45% of pythonsubmissions.

【补充-Python】-递归实现

递归方法很简单,一般都能想到,这里也就不赘述了,用 Python 的递归实现

class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        def dfs(root, res) :
            if root :
                dfs(root.left, res)
                dfs(root.right, res)
                res.append(root.val)
        dfs(root, res)
        return res
67 / 67  test cases passed. Runtime: 40 ms  Your runtime beats 67.45% of pythonsubmissions.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值