38 二叉树的深度

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

思路一:递归的方式

时间复杂度为O(n)

空间复杂度为O(n)

该方法存在堆栈溢出的风险,树的深度如果非常非常非常大 是会出现栈的溢出的

1 import java.lang.Math;
2 public class Solution {
3     public int TreeDepth(TreeNode root) {
4         //考虑特殊情况,空树深度为0
5         if(root == null ) return 0;
6         //左子树的高度和右子树的高度做比较,值较大的,加1,即为树的深度
7         return Math.max( (1+TreeDepth(root.left)),(1+TreeDepth(root.right)));
8     }
9 }

 思路二:利用层次遍历,层的数目就是树的深度

借助于队列

 1 /**
 2 public class TreeNode {
 3     int val = 0;
 4     TreeNode left = null;
 5     TreeNode right = null;
 6     public TreeNode(int val) {
 7         this.val = val;
 8     }
 9 }
10 */
11 import java.util.Queue;
12 import java.util.LinkedList;
13 public class Solution {
14     public int TreeDepth(TreeNode root) {
15         //考虑特殊情况,root为空,返回0
16         if(root==null ) return 0;
17         Queue<TreeNode> queue = new LinkedList<TreeNode>();
18         queue.offer(root);
19         //定义三个变量,其中currentlayer是表明当前层的结点个数
20         //nextlayer是表明下一层的结点个数,这两个结点是为了计算层
21         int depth=0;
22         int curlayer = 0;
23         int nextlayer = 1;
24         while( !queue.isEmpty()){
25             TreeNode top = queue.poll();
26             curlayer++;
27             if(top.left != null){
28                 queue.add(top.left);
29             }
30             if(top.right != null){
31                 queue.add(top.right);
32             }
33             //判断本层的所有的结点是不是都入队列了
34             if(curlayer == nextlayer){
35                 curlayer =0; //重新令当前层为0
36                 nextlayer = queue.size(); //计算下一层
37                 depth++;//遍历了一层,深度加1
38             }
39         }
40         return depth;
41     }
42 }

 

posted @ 2019-07-08 10:36  淡如水94  阅读(120)  评论(0)    收藏  举报