[LeetCode] 111. Minimum Depth of Binary Tree
2017-07-31 20:56
363 查看
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.
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 { public: int minDepth(TreeNode* root) { if (root == nullptr) return 0; if (!root->right) return minDepth(root->left) + 1; // only left branch if (!root->left) return minDepth(root->right) + 1; // only right branch return min(minDepth(root->left), minDepth(root->right)) + 1; // no or two } };
// DFS class Solution { public: int minDepth(TreeNode* root) { if (root == nullptr) return 0; if (root->left == nullptr && root->right == nullptr) return 1; int minDep = INT_MAX; if (root->left) minDep = min(minDep, minDepth(root->left) + 1); if (root->right) minDep = min(minDep, minDepth(root->right) + 1); return minDep; } };
// DFS class Solution { public: int minDepth(TreeNode* root) { if (root == nullptr) return 0; int MinDepth = INT_MAX; minDepth(root, 1, MinDepth); return MinDepth; } private: void minDepth(TreeNode *root, int level, int& MinDepth) { if (root->left == nullptr && root->right == nullptr) MinDepth = min(level, MinDepth); if (root->left) minDepth(root->left, level + 1, MinDepth); if (root->right) minDepth(root->right, level + 1, MinDepth); } };
// BFS class Solution { public: int minDepth(TreeNode* root) { if (root == nullptr) return 0; int level = 1; queue<TreeNode *> q; q.push(root); q.push(nullptr); while (!q.empty()) { TreeNode *ptn = q.front(); q.pop(); if (ptn == nullptr) { level++; if (!q.empty()) q.push(nullptr); continue; } if (ptn->left == nullptr && ptn->right == nullptr) break; else { if (ptn->left) q.push(ptn->left); if (ptn->right) q.push(ptn->right); } } return level; } };
相关文章推荐
- <LeetCode OJ> Invert Binary Tree【226】
- LeetCode 105,106. Construct Binary Tree 重建二叉树 Python Solution
- [LeetCode] 111. Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- [leetcode: Python]104. Maximum Depth of Binary Tree
- leetcode 111. Minimum Depth of Binary Tree
- LeetCode - 111. Minimum Depth of Binary Tree
- LeetCode 226. Invert Binary Tree (反转二叉树)
- 【leetcode】104. Maximum Depth of Binary Tree
- [LeetCode]--104. Maximum Depth of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- Leetcode-标签为Tree 111. Minimum Depth of Binary Tree
- leetcode 545. Boundary of Binary Tree
- LeetCode543. Diameter of Binary Tree
- [Leetcode] binary tree 右视问题
- leetcode111.MinimumDepthofBinary Tree
- [LeetCode] 543. Diameter of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- Leetcode-111. Minimum Depth of Binary Tree
- Leetcode 654. Maximum Binary Tree 最大二叉树 解题报告