LeetCode 树类型题目总结

215 阅读1分钟

前言

关于 LeetCode 数组类型题目的相关解法,可见LeetCode 数组类型题目做前必看,分类别解法总结了题目,可以用来单项提高。觉得有帮助的话,记得多多点赞关注哦,感谢!

树的遍历

前序遍历 递归模板

function preOrder(root) {
    if(!root) return
    print(root.val)
    perOrder(root.left)
    perOrder(root.right)
}

前序遍历 非递归

function perOrder(root) {
    let ans = []
    let stack = []
    if (root) stack.push(root)
    while (stack.length) {
        const now = stack.pop()
        ans.push(now.val)
        if (now.right) stack.push(now.right)
        if (now.left) stack.push(now.left)
    }
    return ans
}

中序遍历 递归

function inOrder(root) {
    if (!root) return
    inOrder(root.left)
    print(root.val)
    inOrder(root.right)
}

中序遍历 非递归

function inOrder(root) {
    let ans = []
    let stack = []
    let curr = root
    while (curr || stack.length) {
        while (curr) {
            stack.push(curr)
            curr = curr.left
        }
        const now = stack.pop()
        ans.push(now.val)
        curr = now.right
    }
}

后序遍历 递归

function bacOrder(root) {
    if (!root) return
    bacOrder(root.left)
    bacOrder(root.right)
    print(root.val)
}

层次遍历

function BFS(root) {
    if (!root) return
    let queue = []
    let ans = []
    queue.push(root)
    while (queue.length) {
        const now = queue.pop()
        ans.push(now.val)
        if (now.left) queue.push(now.left)
        if (now.right) queue.push(now.right)
    }
}

题目汇总