python--lintcode66. 二叉树的前序遍历

给出一棵二叉树,返回其节点值的前序遍历

样例:

给出一棵二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

 返回 [1,2,3].

可以说这一题是很基础了,用递归做:

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

class Solution:
    """
    @param root: A Tree
    @return: Preorder in ArrayList which contains node values.
    """
    def preorderTraversal(self, root):
        # write your code here

        def traversal(root):
            if(root is None):return
            result.append(root.val)
            traversal(root.left)
            traversal(root.right)

        result=[]
        traversal(root)
        return result


Tree = TreeNode(2)
Tree.left = TreeNode(1)
Tree.right = TreeNode(3)
s = Solution()
print(s.preorderTraversal(Tree))


阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页