您的位置:首页 > 其它

LeetCode Minimum Depth of Binary Tree

2014-03-18 16:15 351 查看
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == NULL) return 0;
int min_depth = INT_MAX;
dfs(root, 0, min_depth);
return min_depth + 1;
}

void dfs(TreeNode *root, int cur_depth, int& min_depth) {
if (root == NULL) return;
if (cur_depth >= min_depth) return;
// we come here means that cur_depth < min_depth
if (root->left == NULL && root->right == NULL) { // this is a leaf node
min_depth = cur_depth;
return;
}

dfs(root->left, cur_depth + 1, min_depth);
dfs(root->right, cur_depth + 1, min_depth);
}
};


采用dfs遍历,对于深度已经超过当前已有最小值得路径进行裁剪。不过这个深度的概念,自己的理解和题目中的好像有些偏差。当然也可以用bfs,因为是求最小高度平均时间上bfs能够更早的发现最小高度,但是空间上dfs来的更少。下面是bfs的代码

class Solution {
public:
int minDepth(TreeNode *root) {
if (root == NULL) return 0;
return bfs(root) + 1;
}

int bfs(TreeNode *root) {
if (root == NULL) return 0;
int depth = 0;
int cur_len = 1;
queue<TreeNode*> q;
q.push(root);
bool hasleft = false;
bool hasright= false;
while (!q.empty()) {
while(cur_len--) {
TreeNode* n = q.front();
q.pop();
hasleft = n->left != NULL;
hasright= n->right != NULL;
if (hasleft) {
q.push(n->left);
}
if (hasright) {
q.push(n->right);
}
if (!hasleft && !hasright) return depth;
}
depth++;
cur_len = q.size();
}
return depth;
}
};


第二轮:

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.

dfs的简洁版本:

class Solution {
private:
int mind;
public:
int minDepth(TreeNode *root) {
if (root == NULL) return 0;
if (root->left == NULL) return minDepth(root->right) + 1;
if (root->right == NULL) return minDepth(root->left) + 1;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};


再练一发bfs:

class Solution {
private:
int mind;
public:
int minDepth(TreeNode *root) {
if (root == NULL) {
return 0;
}
queue<TreeNode*> que;
que.push(root);

int depth = 1;
while (!que.empty()) {
int last_len = que.size();
for (int i=0; i<last_len; i++) {
TreeNode* n = que.front();
que.pop();
if (n->left == NULL && n->right == NULL) {
// leaf node
return depth;
}
if (n->left != NULL) {
que.push(n->left);
}

if (n->right != NULL) {
que.push(n->right);
}
}
depth++;
}
return depth;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: