题目
题解
看到题我想到的是使用递归、每遍历一个节点就用一个变量计数加一、等到了最后叶子节点表示已经遍历到最底部、然后用一个外部记录每个根节点深度的变量来找出最大深度的叶子节点。使用的是先序遍历的思想。
题解有后序遍历、和层遍历的题解。
大佬详细题解:面试题55 - I. 二叉树的深度(后序遍历、层序遍历,清晰图解)
class Solution {
private int max = 0;
public int maxDepth(TreeNode root) {
if (root == null){
return max;
}
dfs(root,1);
return max;
}
void dfs(TreeNode root,int ans){
if (root.left == null && root.right == null && max < ans){
max = ans;
return;
}
if (root.left != null){
dfs(root.left,ans + 1);
}
if (root.right != null){
dfs(root.right,ans + 1);
}
}
}