美文网首页leetcode刷题总结 python版
leetcode 144. Binary Tree Preord

leetcode 144. Binary Tree Preord

作者: PJCK | 来源:发表于2019-06-21 22:39 被阅读1次

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

    Example:

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

    Output: [1,2,3]
    Follow up: Recursive solution is trivial, could you do it iteratively?

    python代码

    这个题是用递归求先序遍历。
    里面涉及到extend的用法 而extendappend是有差别的。extendappend的差别

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

    也可以建立一个函数,用于递归遍历:

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

    PS:

    在这个题中如果把extend改为append,将会出错,因为这样最后会得到一个广义表(里面会有null)。
    比如,在上面的样例中,如果用append。最后会得到:
    [1,[],[2,[3,[],[]],[]]],
    如果把方括号改为圆括号,这个就是利用先序遍历表示二叉树的广义表。(广义表是一个递归的表,其含义可以见于严蔚敏的数据结构一书,也可以上网查)

    相关文章

      网友评论

        本文标题:leetcode 144. Binary Tree Preord

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