【LeetCode练习题】Minimum Depth of Binary Tree
Minimum Depth of Binary Tree
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.
和上一题对应,求二叉树的最小深度。
解题思路:
参考上一题Maximun Depth of Binary Tree中最后那个极短的解法。
另外需要判断一下递归返回0的时候的结果不可取,因为不是叶节点。
代码如下:
class Solution { public: int minDepth(TreeNode *root) { if(!root) return 0; int l = minDepth(root->left); int r = minDepth(root->right); if(l * r != 0) return min(l,r)+1; else if(l == 0) return r+1; else return l+1; } };
posted on 2014-04-13 16:31 Allen Blue 阅读(143) 评论(0) 编辑 收藏 举报