Day 14 | 二叉树

57 阅读1分钟

二叉树

左右孩子的结构

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

144. 二叉树的前序遍历

  • 迭代法
    while stack:
        # 倒序来 right left root
        node = stack.pop()
        if node:
            res.append(node.val)
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
  • 递归法
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:

    stack = [root]
    res = []

    def preorder(root):
        if not root:
            return
        res.append(root.val)

        if root.left:
            preorder(root.left)
        if root.right:
            preorder(root.right)

    preorder(root)
    
    return res

94. 二叉树的中序遍历

  • 迭代法

注意访问左子树的方式

        # stack = []
        # res = []

        # while root or stack:
        #     # 一直向左子树走,每一次将当前节点保存到栈中
        #     while root:
        #         stack.append(root)
        #         root = root.left
        #     # 利用栈先进后出
        #     node = stack.pop()
        #     res.append(node.val)
        #     root = node.right
            
        # return res
  • 递归法
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:

    stack = []
    res = []

    def inorder(root):
        if not root:
            return
        if root.left:
            inorder(root.left)
        res.append(root.val)
        if root.right:
            inorder(root.right)
    
    inorder(root)
    
    return res

145. 二叉树的后序遍历

  • 迭代法

过一下每种遍历的顺序,注意迭代法的顺序

while stack:
        # 倒序来 right left root
        node = stack.pop()
        if node:
            res.append(node.val)
            if node.left:
                res.append(node.left)
            if node.right:
                res.append(node.right)
  • 递归法

按顺序写

def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:

    res = []

    def postorder(root):
        if not root:
            return
        if root.left:
            postorder(root.left)
        if root.right:
            postorder(root.right)
        res.append(root.val)
    
    postorder(root)

    return res

统一迭代法

(补)