LeetCode 145 Binary Tree Postorder Traversal (Python)

Posted by 小明MaxMing on February 26, 2022

题目

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

解题思路

递归和非递归两种方法

代码

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
             return []
        return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack, res = [root], deque([])
        while stack:
            cur = stack.pop()
            if cur:
                res.appendleft(cur.val)
                stack.append(cur.left)
                stack.append(cur.right)
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅