求二叉树的深度和二叉树的高度一样的,之前在王道上学习过用层次遍历的方法,这里整理一下递归方法
当前节点的高度等于左子树的高度与右子树高度的最大值+1
int maxDepth(TreeNode* root) {
if(root==NULL)return 0;//空节点的高度是0
int left=maxDepth(root->left);
int right=maxDepth(root->right);
return max(left,right)+1;//注意这里是+1,否则没办法更新啊!
}