首页 > 代码库 > 二叉树的最大深度
二叉树的最大深度
代码:
/**
* 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);
}
};
截图:
二叉树的最大深度