首页 > 其他 > 详细

Minimum Depth of Binary Tree

时间:2014-03-10 07:32:25      阅读:460      评论:0      收藏:0      [点我收藏+]

Maximum Depth of Binary Tree

可以这样写

bubuko.com,布布扣
1 int maxDepth(TreeNode *root) {
2         if(!root)
3             return 0;
4         else
5             return 1+max(maxDepth(root->left),maxDepth(root->right));
6     }
bubuko.com,布布扣

Minimum Depth of Binary Tree

如果仿照上面

bubuko.com,布布扣
1 int minDepth(TreeNode *root) {
2         if(!root)
3             return 0;
4         else
5             return 1+min(minDepth(root->left),minDepth(root->right));
6     }
bubuko.com,布布扣

Status: Wrong Answer

Input: {1,2}
Output: 1
Expected: 2

 

根据这个错误的提示,需要加上两个判断

bubuko.com,布布扣
1 if(!(root->right)&&root->left)
2             return 1+minDepth(root->left);
3         else if(!(root->left)&&root->right)
4             return 1+minDepth(root->right);
bubuko.com,布布扣

AC 完整代码:

bubuko.com,布布扣
 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int minDepth(TreeNode *root) {
13         if(!root)
14             return 0;
15         if(!(root->right)&&root->left)
16             return 1+minDepth(root->left);
17         else if(!(root->left)&&root->right)
18             return 1+minDepth(root->right);
19         else
20             return 1+min(minDepth(root->left),minDepth(root->right));
21     }
22 };
View Code

Minimum Depth of Binary Tree,布布扣,bubuko.com

Minimum Depth of Binary Tree

原文:http://www.cnblogs.com/crane-practice/p/3590421.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!