递归
中序
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def helper(root):
if not root:
return
if root.left:
helper(root.left)
res.append(root.val)
if root.right:
helper(root.right)
helper(root)
return res
迭代
前序
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
stack = []
current = root
while current or stack:
while current:
res.append(current.val)
stack.append(current)
current = current.left
current = stack.pop()
current = current.right
return res