Leetcode 144. Binary Tree Preorder Traversal

参考例子:[8,3,1,6,4,7,10,14,13]

8,3,1 和 6,4 说明从root开始,沿着左臂向下寻找leaf 的过程中应该逐个将node.val push入ans.

 1 class Solution(object):
 2     def preorderTraversal(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: List[int]
 6         """
 7         stack = []
 8         ans = []
 9         while stack or root:
10             while root:
11                 stack.append(root)
12                 ans.append(root.val)
13                 root = root.left
14             root = stack.pop()
15             root = root.right
16         return ans

 

posted @ 2017-01-04 12:11  lettuan  阅读(116)  评论(0)    收藏  举报