#144. 二叉树的前序遍历 (递归与迭代)
题目
给定一个二叉树,返回它的前序遍历。(中间节点,左子树,右子树)
解答
递归解法
- base case:如果根节点为空,则返回 []。
- recursive case:返回 [中间节点] + preorder(左子树) + preorder(右子树)
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
迭代解法
- 创建stack和result,把root加进stack。
- 当stack不等于空时,先把栈顶pop成curr,把curr.val加进result,再依次添加右子树,左子树进栈。
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack = [root]
result = []
while stack:
curr = stack.pop()
result.append(curr.val)
if curr.right:
stack.append(curr.right)
if curr.left:
stack.append(curr.left)
return result
收获
- 前序遍历是对迭代写法最友好的一种!!棒棒!