迭代法
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
stack = [root]
res = []
while stack:
i = stack.pop()
res.append(i.val)
if i.right:
stack.append(i.right)
if i.left:
stack.append(i.left)
return res
递归法:
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def pre(root):
if not root:
return []
res.append(root.val)
pre(root.left)
pre(root.right)
res=[]
pre(root)
return res
迭代统一写法:
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res,stack = [],[]
while stack or root:
if root:
res.append(root.val)
stack.append(root)
root = root.left
else:
tmp = stack.pop()
root = tmp.right
return res