IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 0 Trackbacks
          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.

          本題有兩種解法。
          第一種解法:對二叉樹進行BFS,由于是按層遍歷的,因此如果在某一層發現了一個葉子節點,那么就找到了最小深度,此時返回當前深度即可。實現代碼如下:
           1 public class Solution {
           2     public int minDepth(TreeNode root) {
           3         if (root == nullreturn 0;
           4         int depth = 1;
           5         int currentLevel = 1;
           6         int nextLevel = 0;
           7         Queue<TreeNode> queue = new LinkedList<TreeNode>();
           8         queue.add(root);
           9         while (!queue.isEmpty()) {
          10             TreeNode node = queue.remove();
          11             currentLevel--;
          12             if (node.left == null && node.right == null) {
          13                 return depth;
          14             }
          15             if (node.left != null) {
          16                 queue.add(node.left);
          17                 nextLevel++;
          18             }
          19             if (node.right != null) {
          20                 queue.add(node.right);
          21                 nextLevel++;
          22             }
          23             if (currentLevel == 0) {
          24                 if (nextLevel != 0) {
          25                     depth++;
          26                 }
          27                 currentLevel = nextLevel;
          28                 nextLevel = 0;
          29             }
          30         }
          31         return depth;
          32     }
          33 }

          第二種解法:采用遞歸的思想,分別求左右子樹的最小深度,比較之后返回較小值。實現如下:
           1 public class MinimumDepthofBinaryTree {
           2     public int minDepth(TreeNode root) {
           3         if (root == null)
           4             return 0;
           5         if (root.left == null && root.right == null)
           6             return 1;
           7         else {
           8             int leftDepth = root.left != null ? minDepth(root.left)
           9                     : Integer.MAX_VALUE;
          10             int rightDepth = root.right != null ? minDepth(root.right)
          11                     : Integer.MAX_VALUE;
          12             return Math.min(leftDepth, rightDepth) + 1;
          13         }
          14     }
          15 }
          posted on 2013-12-21 21:19 Meng Lee 閱讀(2265) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 隆尧县| 宁阳县| 昌图县| 临汾市| 偃师市| 建湖县| 吴旗县| 若羌县| 四会市| 临邑县| 翼城县| 胶州市| 广昌县| 济阳县| 望江县| 辽源市| 金乡县| 桐城市| 内丘县| 石棉县| 乐业县| 汝城县| 莱西市| 汝州市| 阿拉尔市| 苍梧县| 富阳市| 中宁县| 上杭县| 江口县| 寿阳县| 瑞丽市| 轮台县| 凤台县| 桐梓县| 鄂温| 陇西县| 嫩江县| 吉木萨尔县| 台中市| 阿瓦提县|