Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
两种递归:
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
int leftmax=maxDepth(root->left)+1;
int rightmax=maxDepth(root->right)+1;
return leftmax>=rightmax?leftmax:rightmax;
}
i
nt maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
int leftmax=0,rightmax=0;
if(!root->left&&!root->right) //leaf node
return 1;
if(root->left&&root->right) { // two sons
leftmax=maxDepth(root->left);
rightmax=maxDepth(root->right);
return leftmax>rightmax?(leftmax+1):(rightmax+1);
}
if(root->left){//only left son
return maxDepth(root->left)+1;
}
if(root->right){//only right son
return maxDepth(root->right)+1;
}
return 0;// control reaches end of non-void function [-Werror=return-type]
}