Minimum Depth of Binary Tree
Maximum Depth of Binary Tree
可以这样写
1 int maxDepth(TreeNode *root) { 2 if(!root) 3 return 0; 4 else 5 return 1+max(maxDepth(root->left),maxDepth(root->right)); 6 }
Minimum Depth of Binary Tree
如果仿照上面
1 int minDepth(TreeNode *root) { 2 if(!root) 3 return 0; 4 else 5 return 1+min(minDepth(root->left),minDepth(root->right)); 6 }
Status: Wrong Answer
Input: | {1,2} |
Output: | 1 |
Expected: | 2 |
根据这个错误的提示,需要加上两个判断
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);
AC 完整代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 };
posted on 2014-03-09 19:25 crane_practice 阅读(201) 评论(0) 编辑 收藏 举报