每天两道LeetCodeHard:(25)

136 阅读1分钟

145. Binary Tree Postorder Traversal

经典题目

题干:

Given a binary tree, return the postorder traversal of its nodes' values.

解释:

返回一个树的后序遍历

思考:

好像非常直白的一个题。。。先写个标准解吧。一行:

class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        return self.postorderTraversal(root.left)+self.postorderTraversal(root.right)+[root.val]

这就是python的魅力啊,list用来拼接元素,这是别的语言想都不敢想的。时间效率86 接下来是模板回答,用迭代方式写遍历二叉树 其实就是用两个指针判断到底是该返回了还是该往右走了。

答案:

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        queue = []  # 数组模拟栈
        last_visit = root
        while root or queue:
            while root:
                queue.insert(0, root)
                root = root.left
            root = queue[0]
            if root.right is None or root.right == last_visit:
                res.append(root.val)
                queue.pop(0)
                last_visit = root
                root = None
            else:
                root = root.right
        return res

答案补充:

注意使用deque的话会比直接用list模拟stack来的慢。