Leetcode 111. Minimum Depth of Binary Tree

来源:互联网 发布:order by sql 编辑:程序博客网 时间:2024/06/07 06:53

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.

s思路:
1. 最短路径。和找最长路径的方法一样啊。。。recursive,二选一
2. 要求到leaf. 即:这个node没有左右child。如果某个节点有左子树,但无右子树,则:应该返回左子树的最短,因为右子树没有,也就没有leaf。
3. 所以要想办法把root到leaf的最短距离精确翻译成代码。min(minDepth(root->left),minDepth(root->right))+1;就没有完全考虑没有左子树或右子树的情况。例如,没有右子树,则右子树返回0,那么最短距离就是1了,这就和要求不符合。因此,需要添加条件判断:
if(!root->left||!root->right)
return max(minDepth(root->left),minDepth(root->right))+1;
详情见代码!

class Solution {public:    int minDepth(TreeNode* root) {        //        if(!root) return 0;        int h1=minDepth(root->left);        int h2=minDepth(root->right);        if(h1==0&&h2>0) return h2+1;//这两句就是把找leaf翻译成编程或数学语言        if(h2==0&&h1>0) return h1+1;        return min(h1,h2)+1;    }};//优化之后!!class Solution {public:    int minDepth(TreeNode* root) {        if (!root) return 0;        if (root->left && root->right)            return min(minDepth(root->left),minDepth(root->right))+1;        else            return max(minDepth(root->left),minDepth(root->right))+1;    }};
0 0
原创粉丝点击