求二叉树的深度
今天我们来了解一下如何求二叉树的深度
方法一:
自上而下
所谓自上而下的方法顾名思义就是从根节点出发每向下一层深度加一到叶子节点更新最大深度直至递归完毕
最后取左右子树其中的的最大深度
自下而上
从叶子节点开始没向上一层深度加一然后取左右最大的深度采用动态规划的思想
道理比较简单看代码自己意会
leetcode里有动画懒得画图可以去看看 探索-二叉树
https://leetcode-cn.com/explore/learn/card/data-structure-binary-tree/3/solve-problems-recursively/11/
自上而下
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return maxDepth(root,1,1);
}
//自顶向上
public int maxDepth(TreeNode root,int answer,int depth){
if(root==null){
return answer;
}
if(root!=null&&root.left==null&&root.right==null){
answer=Math.max(answer,depth);
}
depth+=1;
int answer1=maxDepth(root.left,answer,depth);
int answer2=maxDepth(root.right,answer,depth);
return Math.max(answer1,answer2);
}
}
自下而上
import java.lang.Math;
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return maxDep(root);
}
//自底向上
public int maxDep(TreeNode root){
if(root==null){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}