代码随想录Day14打卡 二叉树(1)

52 阅读1分钟

二叉树的递归遍历

前序遍历

递归遍历的区别在于什么时候把root的val加入res

const preorderTraverse = (root) => {
    const res = []
    const dfs = (node) => {
        if (!node) {
            return
        }
        //先标记遍历过root
        res.push(node.val)
        //遍历左子树
        dfs(node.left)
        //遍历右子树
        dfs(node.right)
    }
    dfs(root)
    return res
}

中序遍历

const inorderTraverse = (root) => {
    const res = []
    const dfs = (node) => {
        if (!node) {
            return
        }
        //遍历左子树
        dfs(node.left)
        //遍历过root
        res.push(node.val)
        //遍历右子树
        dfs(node.right)
    }
    dfs(root)
    return res
}

后序遍历

const postorderTraverse = (root) => {
    const res = []
    const dfs = (node) => {
        if (!node) {
            return
        }
        //遍历左子树
        dfs(node.left)
        //遍历右子树
        dfs(node.right)
        //遍历过root
        res.push(node.val)
    }
    dfs(root)
    return res
}

二叉树的迭代遍历

前序遍历

前序遍历是中左右,所以处理root节点,再push右节点,再push左节点

const preorderTraverse = (root) => {
    const res = []
    const stack = []
    if (root === null) return res
    stack.push(root)
    while (stack.length) {
        const curr = stack.pop()
        res.push(curr.val)
        if (curr.right) stack.push(curr.right)
        if (curr.left) stack.push(curr.left)
    }
    return res
}

中序遍历

因为中序遍历的访问和处理顺序是不同的,所以我们不能用之前的前序法来迭代遍历

const inorderTraverse = (root) => {
    const res = []
    const stack = []
    let curr = root
    while (curr !== null || stack.length) {
        if (curr !== null) {
            stack.push(curr)
            curr = curr.left
        } else {
            curr = stack.pop()
            res.push(curr.val)
            curr = curr.right
        }
    }
    return res
}

后序遍历

再来看后序遍历,先序遍历是中左右,后续遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序,然后在反转result数组,输出的结果顺序就是左右中了

const postorderTraverse = (root) => {
    const res = []
    const stack = []
    if (root === null) return res
    stack.push(root)
    while (stack.length) {
        const curr = stack.pop()
        res.push(curr.val)
        if (curr.left) stack.push(curr.left)
        if (curr.right) stack.push(curr.right)
    }
    return res.reverse()
}