求树的深度

题目描述

  输入一棵二叉树,求该树的深度。
  从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
来自牛客。
 1     public int TreeDepth(TreeNode root) {
 2         //递归实现
 3         /*if(root == null){
 4             return 0;
 5         }
 6         int leftcount = TreeDepth(root.left);
 7         int rightcount = TreeDepth(root.right);
 8         //如果左右子节点都为空,返回0,0再加当前节点1
 9         return Math.max(leftcount , rightcount)+1;
10         */
11         if(root == null) return 0;
12         LinkedList<TreeNode> list = new LinkedList<TreeNode>();
13         list.add(root);
14         //depth为深度,什么情况下深度会加1呢?当把当前这一层所有节点都pop完就进入下一层
15         //那怎么确定计算完当前节点呢?cur累加至当层左右节点pop完,即cur==nextcount
16         int depth = 0,curCount = 0,nextCount = list.size();
17         while(!list.isEmpty()){
18             TreeNode curTree = list.pop();
19             curCount++;
20             if(curTree.left != null){
21                 list.add(curTree.left);
22             }
23             if(curTree.right != null){
24                 list.add(curTree.right);
25             }
26             if(curCount == nextCount){
27                 curCount = 0;
28                 nextCount = list.size();
29                 depth++;
30             }
31         }
32         return depth;
33 
34 
35     }

 

posted on 2019-08-22 17:25  大猫食小鱼  阅读(655)  评论(0编辑  收藏  举报