题目描述
输入一颗二叉树,求该树的深度,从根节点到叶节点依此经过的节点(含根,叶节点)形成树的一条路径,最长路径的长度为树的深度。
解题思路
这道题是我第一次面试的时候上来就要手撕代码,很容易理解,递归就完事了。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
}
}
以上就是这道题的解法。