剑指No.55-1_二叉树的深度
- 题目:输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
示例:例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
- 使用DFS方法
public class MySolution {
int res = 0;
public int maxDepthWay(TreeNode root) {
recur(root, 0);
return res;
}
public void recur(TreeNode root, int k){
if (root == null)
return;
k++;
if (k > res)
res = k;
recur(root.leftNode, k);
recur(root.rightNode, k);
}
}