二叉树的最大深度和最小深度浅析

二叉树的最大深度:

   递归的分别获取左右子树的深度,返回较大的深度,每次加1即可。

代码:

1      public static int maxDepth(TreeNode root){
2          if(root == null){
3              return 0;
4          }
5         int len1 = 1+maxDepth(root.left);
6         int len2 = 1+maxDepth(root.right);
7         return len1 >= len2? len1:len2;
8      }

二叉树的最小深度:

 设置一个深度计数变量

 每次获取二叉树的一层结点,依次遍历该层的结点,第一次遇到叶子结点就返回,此时的深度是最小深度。

 1     public static int minDepth(TreeNode root){
 2         if(root == null){
 3             return 0;
 4         }
 5         //深度计数变量
 6         int height = 0;
 7         //存取该层结点集合
 8         ArrayList<TreeNode> arr = new ArrayList<TreeNode>();
 9         arr.add(root);
10         return minDepth(height,arr);
11     }
12 
13     public static int minDepth(int height, ArrayList<TreeNode> arr) {
14         //存取下一层的结点集合
15         ArrayList<TreeNode> arr1 = new ArrayList<TreeNode>();
16         height++;
17         for(TreeNode tree: arr){
18             //遇到叶子结点就返回
19             if(tree.left == null && tree.right == null){
20                 return height;
21             }
22             
23             if(tree.left != null){
24                 arr1.add(tree.left);
25             }
26             
27             if(tree.right != null){
28                 arr1.add(tree.right);
29             }
30         }
31         return minDepth(height, arr1);
32     }
原文地址:https://www.cnblogs.com/bywallance/p/5570233.html