一、中序遍历

def inorderTraversal(root):
    if not root:
        return []
    return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)

def inorderTraversal(root):
    stack = []
    sol = []
    curr = root
    while stack or curr:
        if curr:
            stack.append(curr)
            curr = curr.left
        else:
            curr = stack.pop()
            sol.append(curr.val)
            curr = curr.right
    return sol

二、前序遍历

def preorderTraversal(root):
    if not root:
        return []
    return [root.val] + inorderTraversal(root.left) + inorderTraversal(root.right)

def preorderTraversal(root):
    stack = []
    sol = []
    curr = root
    while stack or curr:
        if curr:
            sol.append(curr.val)
            stack.append(curr.right)
            curr = curr.left
        else:
            curr = stack.pop()
    return sol

三、后序遍历

def postorderTraversal(root):
    if not root:
        return []
    return inorderTraversal(root.left) + inorderTraversal(root.right) + [root.val]

def postorderTraversal(root):
    stack = []
    sol = []
    curr = root
    while stack or curr:
        if curr:
            sol.append(curr.val)
            stack.append(curr.left)
            curr = curr.right
        else:
            curr = stack.pop()
    return sol[::-1]
01-25 13:17