【算法16天:Day16】第六章二叉树 LeetCode 二叉树的最小深度(111)

92 阅读2分钟

题目二:

image.png

解题思路:

  • 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
  • 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)
  1. 确定递归函数的参数

参数为要传入的二叉树根节点

代码如下:

var getDepth = function(node) {}
  1. 确定终止条件

终止条件也是遇到空节点返回0,表示当前节点的高度为0。

代码如下:

if (node == NULL) return 0;
  1. 确定单层递归的逻辑

这块和求最大深度可就不一样了,一些同学可能会写如下代码:

int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
int result = 1 + min(leftDepth, rightDepth);
return result;

这就重新审题了,题目中说的是:最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 ,注意是叶子节点

什么是叶子节点,左右孩子都为空的节点才是叶子节点!

image.png

如果这么求的话,没有左孩子的分支会算为最短深度。

所以,如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。

反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。

最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。

遍历的顺序为后序(左右中),可以看出:求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。

var minDepth = function(root) {
    if (root === null) return 0
    // 当一个左子树为空,右不为空,这时并不是最低点
    if (root.left === null && root.right !== null) return 1 + minDepth(root.right)
    // 当一个右子树为空,左不为空,这时并不是最低点
    if (root.left !== null && root.right === null) return 1 + minDepth(root.left)
    return 1 + Math.min(minDepth(root.left), minDepth(root.right))
};
// 或者

const minDepth = (root) => {
    if (root == null) {            // 递归到null节点,返回高度0
        return 0;
    }
    if (root.left && root.right) { // 左右子树都存在,当前节点的高度1+左右子树递归结果的较小值
        return 1 + Math.min(minDepth(root.left), minDepth(root.right));
    } else if (root.left) {        // 左子树存在,右子树不存在
        return 1 + minDepth(root.left);
    } else if (root.right) {       // 右子树存在,左子树不存在
        return 1 + minDepth(root.right);
    } else {                       // 左右子树都不存在,光是当前节点的高度1
        return 1;
    }
};

解法二:(迭代法)

var minDepth = function(root) {
    if(!root) return 0;
    const queue = [root];
    let dep = 0;
    while(true) {
        let size = queue.length;
        dep++;
        while(size--){
            const node = queue.shift();
            // 到第一个叶子节点 返回 当前深度 
            if(!node.left && !node.right) return dep;
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
        }
    }
};