比较简单,主要是2种思路
- 前序中序后序遍历时,记录当前节点的深度,并传入子节点,当叶子节点时,进行比较
《二叉树(#144 前序遍历、#94中序遍历、#145后序遍历)》 - 利用层序遍历,那么层的数值就是树深度
我们这里才用第一种,前序遍历:
class Solution {
int maxDep = 0;
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
maxDepth(root,0);
return maxDep;
}
public void maxDepth(TreeNode root,int dept) {
dept++;
if(root.left!=null){
maxDepth(root.left,dept);
}
if(root.right!=null){
maxDepth(root.right,dept);
}
if(root.left==null && root.right==null){
maxDep = max(maxDep,dept);
}
}
int max(int a,int b ){
if(a>b){
return a;
}
return b;
}
}