思路
跟104大差不差却又多了一点条件
- 他是找根节点到叶子结点的最短路径,因此要把根节点也算进去,左右NULL时return1
- 只有1,2的时候,他不能再取左右最小值了,因为右边没有叶子节点,如果无脑递归就会出错,本来答案2就会为1
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| int min(int a,int b){ return a<b?a:b; } int minDepth(struct TreeNode* root) { if(root==NULL){ return 0; } else if(root->left==NULL&&root->right==NULL){ return 1; } else if(root->left==NULL){ return minDepth(root->right)+1; } else if(root->right==NULL){ return minDepth(root->left)+1; } else{ return min(minDepth(root->left)+1,minDepth(root->right)+1); } }
|
就是会有点慢
官方题解也打一份:
官方是先判断左!=NULL,进入递归,再右!=NULL,进入递归,然后还有一个min_depth进行判断大小
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| int minDepth(struct TreeNode *root) { if (root == NULL) { return 0; }
if (root->left == NULL && root->right == NULL) { return 1; }
int min_depth = INT_MAX; if (root->left != NULL) { min_depth = fmin(minDepth(root->left), min_depth); } if (root->right != NULL) { min_depth = fmin(minDepth(root->right), min_depth); }
return min_depth + 1; }
作者:力扣官方题解 链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/solutions/382646/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|
说实话跟我一样慢