leetcode 111 : 二叉树的最小深度
题目
算法思想:我们用dfs的思想解决,如果根节点为空返回0,否则若根节点的左右子树都为空则返回1,都不为空则返回最小高度加一。如果一颗子树为空,另一颗子树不为空,则为空的子树的返回值肯定是0,那我们返回另一个不为空子树的高度加一。
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1;
int l_h = minDepth(root->left);
int r_h = minDepth(root->right);
int rev;
if(l_h == 0)
return r_h+1;
if(r_h == 0)
return l_h+1;
rev = min(r_h,l_h)+1;
return rev;
}