题目描述:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

思路:比较每一条路径的长度,取最大值

ac代码:

 1 /**
 2 public class TreeNode {
 3     int val = 0;
 4     TreeNode left = null;
 5     TreeNode right = null;
 6 
 7     public TreeNode(int val) {
 8         this.val = val;
 9 
10     }
11 
12 }
13 */
14 public class Solution {
15     public int TreeDepth(TreeNode root) {
16         if(root!=null)
17             dfs(root,0);
18         return max;
19     }
20      int max=0;
21      void  dfs(TreeNode root,int t){
22         t++;
23         if(root.left==null&&root.right==null){
24             max=Math.max(max, t);
25         }
26         if(root.left!=null){
27             dfs(root.left,t);
28         }
29         if(root.right!=null){
30             dfs(root.right,t);
31         }
32     }
33 }

 

 posted on 2018-04-12 18:30  几缕清风依旧  阅读(130)  评论(0编辑  收藏  举报