题目:
给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
思路:
不断往下遍历,每往深层遍历一层,深度加一,当遍历到null,与当前最大深度比较,判断是否需要更新。当遍历完所有路径时,即得到了最大深度。
class Solution {
int max = 0;
public int maxDepth(TreeNode root) {
if(root == null){
return max;
}
process(root, 1);
return max;
}
public void process(TreeNode root, int depth){
if(root == null){
max = Math.max(max, depth-1);
return;
}
process(root.left, depth+1);
process(root.right, depth+1);
}
}