http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
class Solution {
public:
// !!!
// root==NULL doesn't indicate leaf node
// root->left==root->right==NULL does indicate leaf node
int minDepth2(TreeNode *root){
if(root->left==root->right) return 1;
else if(root->left!=NULL&&root->right!=NULL) return min(minDepth2(root->left), minDepth2(root->right))+1;
else if(root->left!=NULL) return minDepth2(root->left)+1;
else return minDepth2(root->right)+1;
}
// If the real root is NULL, then the answer is 0
int minDepth(TreeNode *root) {
if(root==NULL) return 0;
return minDepth2(root);
}
};
本文介绍了一种求解二叉树最小深度的方法。通过递归方式遍历左右子节点,判断叶子节点并返回最小路径长度。核心在于正确处理空节点及单一子节点的情况。
1354

被折叠的 条评论
为什么被折叠?



