leetcode 145. Binary Tree Postor

作者: PJCK | 来源:发表于2019-06-23 07:24 被阅读0次

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

    Input: [1,null,2,3]
       1
        \
         2
        /
       3
    
    Output: [3,2,1]
    

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

    这个和leetcode144类似,是利用递归求后序遍历。

    python代码:

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

    相关文章

      网友评论

        本文标题:leetcode 145. Binary Tree Postor

        本文链接:https://www.haomeiwen.com/subject/vgabqctx.html