1. 题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
2. 题目分析
对于二叉树的深度求值,采取递归,递归其左子树和右子树中最大的+1(root结点),最后返回即
3. 题目代码
public class Solution { public int TreeDepth(TreeNode root) { if (root == null) { return 0; } else { int h2 = 0; int h3 = 0; int h1 = 1; h2 = TreeDepth(root.left); h3 = TreeDepth(root.right); h1 = h1 + Math.max(h3, h2); return h1; } } }