[LeetCode] 111. Minimum Depth of Binary Tree
来源:互联网 发布:联赢软件 编辑:程序博客网 时间:2024/05/24 02:12
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.
// DFSclass 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 }};
// DFSclass 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; }};
// DFSclass 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); }};
// BFSclass 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; }};
阅读全文
0 0
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- leetcode-111. Minimum Depth of Binary Tree
- LeetCode-111.Minimum Depth of Binary Tree
- LeetCode 111.Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- [leetcode]111.Minimum Depth of Binary Tree
- 111.[Leetcode]Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- 【leetcode】111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- 1091. Acute Stroke (30)三维广搜
- Birthday Paradox(生日悖论)
- POJ
- 用for循环打印菱形
- bzoj3517: 翻硬币
- [LeetCode] 111. Minimum Depth of Binary Tree
- 幸福的道路(race)
- OpenCL tutorial
- Python学习笔记——分支循环
- 并行算法设计--Foster的设计方法论
- 异常提示
- 实验吧:最近听说刘翔离婚了
- Java权重概率工具类
- C++学习(63)