方法一:迭代代码一:
class Solution(object):
# 迭代
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
pre_stack = [root]
ans = []
while pre_stack:
cur = pre_stack.pop()
ans.append(cur.val)
if cur.right:
pre_stack.append(cur.right)
if cur.left:
pre_stack.append(cur.left)
return ans
迭代代码二:
class Solution(object):
# 迭代
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
pre_stack = []
ans = []
cur = root
while pre_stack or cur:
while cur:
ans.append(cur.val)
pre_stack.append(cur)
cur = cur.left
temp = pre_stack.pop()
cur = temp.right
return ans
方法二:递归
class Solution(object):
# 递归
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)