问题描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
问题解决
二叉树,使用递归解决
class Solution {
int max;
public int maxDepth(TreeNode root) {
if(root == null) return max;
getMaxDepth(root, 1);
return max;
}
public void getMaxDepth(TreeNode root, int depth) {
if(root == null) return;
max = Math.max(depth, max);
getMaxDepth(root.left, depth + 1);
getMaxDepth(root.right, depth + 1);
}
}