您的位置:首页 > 其它

Leetcode 111. Minimum Depth of Binary Tree

2018-01-15 19:40 351 查看
Depth-first search

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

// Depth-first search
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
if (left == 0) return 1 + right;
if (right == 0) return 1 + left;
return 1 + min(left, right);
}
};


Breadth-first search

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

//Breadth-first search
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
deque<TreeNode*> q;
q.push_front(root);
int ret = 1;
while (!q.empty()) {
int n = q.size();
for (int i = 0; i != n; ++i) {
TreeNode* r = q.back();
q.pop_back();
if (r->left == nullptr && r->right == nullptr) return ret;
if (r->right != nullptr) q.push_front(r->right);
if (r->left != nullptr) q.push_front(r->left);
}
++ret;
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: