分别递归遍历左右子树,并且做比较,选取深度大的一支
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
int lhight, rhight;
if (root == NULL) {
return 0;
}
lhight = maxDepth(root->left);
rhight = maxDepth(root->right);
if (lhight > rhight) {
return lhight+1;
}
else
return rhight+1;
}
};
原文:http://www.cnblogs.com/ye-chen/p/7789163.html