📝Leetcode 104 二叉树的最大深度

114 阅读1分钟

题目🌵

📝Leetcode 二叉树的最大深度

✏️leetcode-cn.com/problems/ma…


给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

节点的左子树只包含 小于 当前节点的数。 节点的右子树只包含 大于 当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

输入:root = [2,1,3] 输出:true

解题思路💡

递归

var maxDepth = function (root) {
    if (!root) return 0
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};

image-20220131160753511

迭代

  • 按层搜索 BFS遍历
var maxDepth = function (root) {
    // 迭代法
    if (!root) return 0
    let queue = [] //用数组模拟队列
    let depth = 0 //记录深度
    queue.push(root)
    while (queue.length) {
        const size = queue.length
        for (let i = 0; i < size; i++) {
            const current = queue.shift()//依次推出当前层的所有节点
            if (current.left) {
                queue.push(current.left)
            }
            if (current.right) {
                queue.push(current.right)
            }
        }
        depth += 1
    }
    return depth
};

image-20220131164855686