算法: 145. 后序遍历二叉树Binary Tree Postorder Traversal

Posted AI架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 145. 后序遍历二叉树Binary Tree Postorder Traversal相关的知识,希望对你有一定的参考价值。

145. Binary Tree Postorder Traversal

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

Example 1:

Input: root = [1,null,2,3]
Output: [3,2,1]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Constraints:

  • The number of the nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Follow up: Recursive solution is trivial, could you do it iteratively?

递归求解 - 计算机逆向思维

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root: return []
        res = []
        res += self.postorderTraversal(root.left)
        res += self.postorderTraversal(root.right)
        res.append(root.val)

        return res

遍历求解 - 顺序求解

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        stack = [(root, False)]
        while stack:
            node, isVisited = stack.pop()
            if not node: continue
            if isVisited:
                res.append(node.val)
            else:
                stack.append((node, True))
                stack.append((node.right, False))
                stack.append((node.left, False))

        return res

以上是关于算法: 145. 后序遍历二叉树Binary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 145. 二叉树的后序遍历(Binary Tree Postorder Traversal)

LeetCode 145. 二叉树的后序遍历 (用栈实现后序遍历二叉树的非递归算法)

LeetCode 145. 二叉树的后序遍历

Leetcode 145. 二叉树的后序遍历

145 Binary Tree Postorder Traversal 二叉树的后序遍历

LeetCode 0145. 二叉树的后序遍历:二叉树必会算法