剑指offer_二叉树的深度

题目描述

从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

 

 方法一:利用层次遍历

 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 import java.util.*;
15 public class Solution {
16     public int TreeDepth(TreeNode root) {
17         if(root==null) return 0;
18         Queue<TreeNode> queue = new LinkedList<>();
19         queue.add(root);
20         int depth = 0,count =0,nextCount=1;
21         while(queue.size()!=0){
22             TreeNode top = queue.poll();
23             count++;
24             if(top.left!=null)
25                 queue.add(top.left);
26             if(top.right!=null)
27                 queue.add(top.right);
28             if(count==nextCount){
29                 nextCount=queue.size();
30                 count=0;
31                 depth++;
32             }
33         }
34                 return depth;
35     }
36 }

方法二:

递归方法

1 public int TreeDepth(TreeNode root) {
2 return root == null ? 0 : 1 + Math.max(TreeDepth(root.left), TreeDepth(root.right));
3 }

 

posted @ 2019-09-11 10:26  chyblogs  阅读(85)  评论(0)    收藏  举报