LeetCode | Minimum Depth of Binary Tree

来源:互联网 发布:淘宝店铺装修添加宝贝 编辑:程序博客网 时间:2024/06/06 09:51

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.


需要注意的一点是

当左孩子不为空而右孩子为空的时候,说明此时右边孩子返回的0并不是叶子节点,而是空节点的值。
而这一点表明它并不是叶子节点。
所以叶子节点应当还在左侧,故需要返回左侧子树的最小高度+1

如下图:
图片
应当返回的值是2.但是如果类似于求树的高度,直接使用min(left,height)+1会导致返回的值始终是1

因为在这个时候右子树为空,左子树不为空(2),最近的叶子节点还在左侧。

class Solution {public:    int minDepth(TreeNode* root) {        if(!root) return 0;        int left=minDepth(root->left);        int right=minDepth(root->right);        //表示已经找到叶子节点        if(left==0 && right==0) return 1;        //如果二者只有一个为0,则表示其中一棵子树为空        //故这棵为空的子树的高度不应当算给整体高度,而应当单独处理        if(left==0) return right+1;        if(right==0) return left+1;        return min(left,right)+1;    }};
0 0