Binary Tree Preorder Traversal
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?
Solution:
递归解法很简单:
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 # @param {TreeNode} root 10 # @return {integer[]} 11 def preorderTraversal(self, root): 12 if root == None: 13 return [] 14 else: 15 return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
迭代版本也是常规的将递归改成迭代的版本:
用一个栈来模拟递归的过程,注意栈 FILO 的特点。所以,对于当前根,要把右子树先加入栈,然后再把左子树加入栈。
前序遍历的顺序是:根 - 左子树 - 右子树。
代码如下:
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 # @param {TreeNode} root 10 # @return {integer[]} 11 def preorderTraversal(self, root): 12 stack = [] 13 path = [] 14 if root != None: 15 stack.append(root) 16 while stack != []: 17 e = stack.pop() 18 path.append(e.val) 19 if e.right != None: 20 stack.append(e.right) 21 if e.left != None: 22 stack.append(e.left) 23 return path
[ by Maples7 ]
[ Copyright @Maples7,转载请注明出处。 ]