LeetCode 144. Binary Tree Preorder Traversal 20170706
2017-07-06 11:30 方小呆dai 阅读(131) 评论(0) 编辑 收藏 举报Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
题目大意:给定一棵树,返回它的前序遍历结果。
解题思路:本题难度不大,想了一下,最简单的做法还是递归,先判断当前节点是否为空,如果不为空,则把当前的值加入集合当中,然后递归左子树和右子树,在递归时将其结果与原集合取并集。
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
A = []
if root != None:
A.append(root.val)
left = self.preorderTraversal(root.left)
A.extend(left)
right = self.preorderTraversal(root.right)
A.extend(right)
return A