Leetcode 111. Minimum Depth of Binary Tree
2018-01-15 19:40
351 查看
Depth-first search
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) {} * }; */ // 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; } };
相关文章推荐
- 【LeetCode】111. Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- 【LeetCode】104. Maximum Depth of Binary Tree (2 solutions)
- leetcode 104. Maximum Depth of Binary Tree
- leetcode 543. Diameter of Binary Tree
- [LeetCode] 111. Minimum Depth of Binary Tree
- leetcode 每日一题 111. Minimum Depth of Binary Tree
- Leetcode Everyday: 104. Maximum Depth of Binary Tree
- [leetcode: Python]104. Maximum Depth of Binary Tree
- LeetCode 545. Boundary of Binary Tree
- leetcode解题报告:104. Maximum Depth of Binary Tree
- leetcode-104. Maximum Depth of Binary Tree
- LeetCode——Binary Tree Inorder Traversal
- LeetCode 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- Leetcode-标签为Tree 111. Minimum Depth of Binary Tree
- LeetCode543. Diameter of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree