码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Minimum Depth of Binary Tree

时间:2015-08-15 19:52:05      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

This problem is just similar to Minimum Depth of Binary Tree.

The first solution also uses recursion (not sure whether it can be called DFS).

1 class Solution {
2 public:
3     int minDepth(TreeNode* root) {
4         if (!root) return 0;
5         if (!(root -> left)) return minDepth(root -> right) + 1;
6         if (!(root -> right)) return minDepth(root -> left) + 1;
7         return min(minDepth(root -> left), minDepth(root -> right)) + 1;
8     }
9 }; 

Well, the above code may be compressed into 1 line using nested conditional statements. But I tend to keep its logic clear.

The second solution adopts a level-order traversal (BFS) with a queue. We use two bool variables lt and rt to detect leaf nodes.

 1 class Solution {
 2 public:
 3     int minDepth(TreeNode* root) {
 4         int depth = 0;
 5         if (!root) return depth;
 6         queue<TreeNode*> level;
 7         level.push(root);
 8         while (!level.empty()) {
 9             depth++;
10             int n = level.size();
11             for (int i = 0; i < n; i++) {
12                 bool lt = true, rt = true;
13                 TreeNode* node = level.front();
14                 level.pop();
15                 if (node -> left) level.push(node -> left);
16                 else lt = false;
17                 if (node -> right) level.push(node -> right);
18                 else rt = false;
19                 if (!lt && !rt) return depth;
20             }
21         }
22     } 
23 };

 

[LeetCode] Minimum Depth of Binary Tree

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4732916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!