# 递归
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root: # 空树
return []
left = self.preorderTraversal(root.left)
right = self.preorderTraversal(root.right)
return [root.val] + left + right
# 递归另外一种写法
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def preorder(root: TreeNode):
if not root: # 空树
return []
res.append(root.val)
preorder(root.left)
preorder(root.right)
res = []
preorder(root)
return res
# Morris遍历
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
if not root:
return res
p1 = root
while p1:
p2 = p1.left
if p2:
while p2.right and p2.right != p1:
p2 = p2.right
if not p2.right:
res.append(p1.val)
p2.right = p1
p1 = p1.left
continue
else:
p2.right = None
else:
res.append(p1.val)
p1 = p1.right
return res