1、题目描述(来自牛客,leetcode也有一样的题目Leetcode-104. Maximum Depth of Binary Tree):
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
2、思路:动态规划的思想:记子树i的层数为f(i),i 的左右子树分别为left、right则
f(i) = 1+max{f(left),f(right)}
3、代码:
public int treeDepth(TreeNode root) {
if(root == null){
return 0;
}
if(root.left == null && root.right == null){
return 1;
}
return 1 + Math.max(treeDepth(root.left), treeDepth(root.right));
}