求二叉树的最小深度

101 阅读2分钟

题目描述

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

示例 1:

image.png

输入: root = [3,9,20,null,null,15,7]
输出: 2

思路

这道题跟我们做过的求二叉树的最大深度很相似,那是不是可以用求二叉树的最大深度的思路来做呢?

image.png

直接上代码:

// 返回最小深度
function minDepth(root: TreeNode | null): number {
   return  getDepth(root);
};

// 后序遍历(左右中)得到最小深度
function getDepth(currentNode: TreeNode | null): number{
    // 判断当前节点是否为null
    if(currentNode==null) return 0;
    //递归遍历左右子树的高度
    let leftDepth=getDepth(currentNode.left);
    let rightDepth=getDepth(currentNode.right);
    
    // 返回最小高度
    return Math.min(leftDepth+1,rightDepth+1);
}

此时,我们将root = [3,9,20,null,null,15,7]输入进行测试,得到2,答案符合!

image.png

我们再将root = [3,null,20,15,7] 输入进行测试,得到1这时候就有问题了!

image.png

明明高度应该是3呀!怎么得到的结果是1呢?

image.png

答案很简单,我们将上述二叉树画完整便可一目了然了:

image.png

使用上述代码逻辑,会将节点3左节点null计算在内,这样二叉树的最小深度便是为null的左子树+1,所以便得到了意料之外的答案。那我们怎么来解决这种问题呢?还是直接上代码:

function minDepth(root: TreeNode | null): number {
   return  getDepth(root);
};

// 后序遍历(左右中)
function getDepth(currentNode: TreeNode | null): number{
    // 判断当前节点是否为null
    if(currentNode==null) return 0;
    //递归遍历左右子树的高度
    let leftDepth=getDepth(currentNode.left);
    let rightDepth=getDepth(currentNode.right);
    
    // 处理单侧子树为null的情况
    if(currentNode.left==null&&currentNode.right!=null){
        return rightDepth+1;
    }

    if(currentNode.right==null&&currentNode.left!=null){
        return leftDepth+1;
    }
    
    
    // 返回最小高度
    return Math.min(leftDepth+1,rightDepth+1);
}

代码中处理单侧为null的情况部分便是解决问题的关键,当单侧为null时,直接返回另一侧的高度+1,这样得到的答案便没问题了。

总结

二叉树的最小深度的实现思路与最大深度基本一致,只是需要处理下特殊情况。该题还可以使用前序遍历来做,思路也跟二叉树的最大深度里我写的前序遍历的思路一致,有兴趣的小伙伴可以试一试。以上便是求二叉树的最小深度的所有内容了,如有错误之处,欢迎大家留言指出。

image.png