111.minimum depth of binary tree

题目链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/

题目大意:求解二叉树的最小高度。

法一:BFS。新写一个class,承接TreeNode和当前结点高度。代码如下(耗时6ms):

 1     static class MergeTree {
 2         TreeNode root;
 3         int depth;
 4         MergeTree(TreeNode r, int d) {
 5             root = r;
 6             depth = d;
 7         }
 8     }
 9     public int minDepth(TreeNode root) {
10         int res = Integer.MAX_VALUE;
11         if(root == null) {
12             return 0;
13         }
14         Queue<MergeTree> q = new LinkedList<MergeTree>();
15         MergeTree mT = new MergeTree(root, 1);
16         q.offer(mT);
17         while(!q.isEmpty()) {
18             MergeTree tmpT = q.poll();
19             TreeNode tmpN = tmpT.root;
20             if(tmpN.left != null) {
21                 mT = new MergeTree(tmpN.left, tmpT.depth + 1);
22                 q.offer(mT);
23             }
24             if(tmpN.right != null) {
25                 mT = new MergeTree(tmpN.right, tmpT.depth + 1);
26                 q.offer(mT);
27             }
28             if(tmpN.left == null && tmpN.right == null) {
29                 res = Math.min(res, tmpT.depth);
30             }
31         }
32         return res;
33     }
View Code

同BFS,这里用两个queue,一个queue承接结点,一个queue承接当前结点的高度,免去新建一个class。代码如下(耗时8ms):

 1     public int minDepth(TreeNode root) {
 2         int res = Integer.MAX_VALUE;
 3         if(root == null) {
 4             return 0;
 5         }
 6         Queue<TreeNode> q = new LinkedList<TreeNode>();
 7         Queue<Integer> de = new LinkedList<Integer>();
 8         q.offer(root);
 9         de.offer(1);
10         while(!q.isEmpty()) {
11             TreeNode tmp = q.poll();
12             int t = de.poll();
13             if(tmp.left != null) {
14                 q.offer(tmp.left);
15                 de.offer(t + 1);
16             }
17             if(tmp.right != null) {
18                 q.offer(tmp.right);
19                 de.offer(t + 1);
20             }
21             if(tmp.left == null && tmp.right == null) {
22                 res = Math.min(res, t);
23             }
24         }
25         return res;
26     }
View Code

法二:DFS。竟然这个快这么多。代码如下(耗时1ms):

 1     public int minDepth(TreeNode root) {
 2         if(root == null) {
 3             return 0;
 4         }
 5         return dfs(root, Integer.MAX_VALUE, 1);
 6     }
 7     private static int dfs(TreeNode root, int res, int cnt) {
 8         if(root.left == null && root.right == null) {
 9             return Math.min(res, cnt);
10         }
11         if(root.left != null) {
12             res = dfs(root.left, res, cnt + 1);
13         }
14         if(root.right != null) {
15             res = dfs(root.right, res, cnt + 1);
16         }
17         return res;
18     }
View Code

 

posted on 2018-03-14 10:33  二十年后20  阅读(173)  评论(0编辑  收藏  举报

导航