104. 二叉樹的最大深度 111. 二叉樹的最小深度
阿新 • • 發佈:2019-01-28
104. 二叉樹的最大深度
思路:遞迴的方式,
int maxDepth(TreeNode* root) {
if(!root)
return 0;
else
{
int a=1,b=1;
a+=maxDepth(root->left);
b+=maxDepth(root->right);
return(a>b? a:b);
}
}
111. 二叉樹的最小深度
1 int minDepth(TreeNode* root) { 2 int a=1,b=1; 3 if(!root) 4 return 0; 5 if(root->left!=NULL &&root->right!=NULL) 6 { 7 a+=minDepth(root->left); 8 b+=minDepth(root->right); 9 return (a<=b? a:b); 10 } 11 else if(root->left==NULL ||root->right==NULL) 12 { 13 a+=minDepth(root->left); 14 b+=minDepth(root->right); 15 return (a>=b? a:b); 16 } 17 }