代码:
/**
* 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 height(TreeNode *root)
{
int lheight,rheight;
if(root==NULL) return 0;
lheight=height(root->left);//遍历左子树
rheight=height(root->right);//遍历右子树
if(lheight>rheight)//若左子树的深度大
return lheight+1;
else return rheight+1;
}
int maxDepth(TreeNode *root) {
// write your code here
return height(root);
}
};
截图:
时间: 2024-10-24 02:42:33