参考例子:[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
Leetcode 144. Binary Tree Preorder Traversal
原文:http://www.cnblogs.com/lettuan/p/6248146.html