给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数
解题思路
深度优先遍历,往下一层就深度加一,返回减一,保留最大值
代码
class Solution {
int result = 0;
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root, 1);
return result;
}
private void dfs(TreeNode root, int depth) {
if (root == null) {
return;
}
dfs(root.left, depth + 1);
result = Math.max(result, depth);
dfs(root.right, depth + 1);
}
}