试题
考点

数据结构-二叉树-二叉树遍历

面5笔5

如何计算二叉树的最大深度

前往“校招VIP”小程序,刷题更快
最新校招难题刷题,快来进刷题群吧
解答

1.采用递归思想:一棵树树的最大深度 == 1+左子树的最大深度+右子树的最大深度

2.代码

public  int maxDepth(TreeNode root ){
if(root == null){ //如果为空树返回深度为0
return 0;
}
if(root.left == null && root.right == null){
return 1; //只有根节点返回1即可
}
int leftMax = maxDepth(root.left); //递归求出左子树的深度
int rightMax = maxDepth(root.right);//递归求出右子树的深度
return 1 + (leftMax > rightMax ? leftMax : rightMax);
}

评论

我叫新账号

2021-09-10 23:50:00

0 0

加载更多