题目:二叉树的最大深度
问题描述:给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的距离。
思路:如果根节点为空,则深度为0;如果根节点不为0,则分别求左子树的深度和右子树的深度,哪个大输出哪个并加一。
代码:
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
int lmax,rmax;
if(root==NULL) return 0;
if(root!=NULL){
lmax=maxDepth(root->left);
rmax=maxDepth(root->right);
if(lmax>=rmax) return lmax+1;
else return rmax+1;
}
}
};
感想:做这道题的时候忽略了根节点的深度就是1,只返回左子树的深度或者右子树的深度,没有加一,一直wrong answer。以后一定要注意根节点的深度就是1。