LeetCode: Minimum Depth of Binary Tree 解题报告

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

SOLUTION 1:

递归

这种递归解法更简单。因为在本层递归中不需要考虑左右子树是否为NULL的情况。因为我们直接
把 null 设置为返回一个最大值,这样的话,如果出现空子树,它不会影响最小值。但是如果左
右均为空,则应返回1(即是仅仅为根节点)
        
而且这种做法更加合理。 因为如果是空树,应该是无法到达才是。这时就应该将值设置为最大。

 1 // SOLUTION 1:
 2     public int minDepth1(TreeNode root) {
 3         /*
 4          主页君认为,在这应该是属于未定义行为,这里我们定义为MAX会比较好,因为
 5          null就是取不到任何节点,没有path,不应该将最小值定为0.
 6         */
 7         if (root == null) {
 8             return 0;
 9         }
10         
11         return dfs(root);
12     }
13     
14     /*
15      *  The Recursion Version:
16      *  这种递归解法更简单。因为在本层递归中不需要考虑左右子树是否为NULL的情况。因为我们直接
17         把 null 设置为返回一个最大值,这样的话,如果出现空子树,它不会影响最小值。但是如果左
18         右均为空,则应返回1(即是仅仅为根节点)
19         
20         而且这种做法更加合理。 因为如果是空树,应该是无法到达才是。这时就应该将值设置为最大。
21      * */
22     public int dfs(TreeNode root) {
23         if (root == null) {
24             return Integer.MAX_VALUE;
25         }
26         
27         // The base case: the root is a leaf.
28         if (root.left == null && root.right == null) {
29             return 1;
30         }
31         
32         return Math.min(dfs(root.left), dfs(root.right)) + 1;
33     }
View Code

SOLUTION 2:

使用level traversal会更快。因为我们要的是最短深度。当达到叶子节点 就可以直接退出了。

 1 // SOLUTION 2: 
 2     // Level Traversal:
 3     public int minDepth(TreeNode root) {
 4         /*
 5          主页君认为,在这应该是属于未定义行为,这里我们定义为MAX会比较好,因为
 6          null就是取不到任何节点,没有path,不应该将最小值定为0.
 7         */
 8         if (root == null) {
 9             return 0;
10         }
11         
12         int level = 0;
13         
14         Queue<TreeNode> q = new LinkedList<TreeNode>();
15         q.offer(root);
16         
17         while (!q.isEmpty()) {
18             int size = q.size();
19             level++;
20             for (int i = 0; i < size; i++) {
21                TreeNode cur = q.poll();
22                
23                if (cur.left == null && cur.right == null) {
24                    return level;
25                }
26                
27                if (cur.left != null) {
28                    q.offer(cur.left);
29                }
30                
31                if (cur.right != null) {
32                    q.offer(cur.right);
33                }
34             }
35         }
36         
37         return 0;
38     }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/MinDepth_1218_2014.java

posted on 2014-12-18 22:59  Yu's Garden  阅读(565)  评论(0编辑  收藏  举报

导航