题目描述:
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.
这种题型显然应该采用递归的方法,从任意一个节点开始的最大高度等于它的左右子树高度的最大值加一。class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
else if(root->left==NULL&&root->right==NULL)
return 1;
else if(root->left==NULL&&root->right!=NULL)
return 1+maxDepth(root->right);
else if(root->left!=NULL&&root->right==NULL)
return 1+maxDepth(root->left);
else if(root->left!=NULL&&root->right!=NULL)
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};