LeetCode Minimum Depth of Binary Tree 最小深度二叉树
2013-11-06 08:02
453 查看
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.
本题思路:
1. 每进入一层用一个变量(这里是levelNum)记录当前从根节点到这一层节点的节点数
2. 当到达叶子节点的时候,就记录当前最小深度overall
2. 当所有的叶子节点都到达一遍之后,就得到了最终最小深度overall。
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
本题思路:
1. 每进入一层用一个变量(这里是levelNum)记录当前从根节点到这一层节点的节点数
2. 当到达叶子节点的时候,就记录当前最小深度overall
2. 当所有的叶子节点都到达一遍之后,就得到了最终最小深度overall。
class Solution { public: int minDepth(TreeNode *root) { if(root == nullptr) return 0; int overall = INT_MAX; int levelNum = 0; minD(root, overall, levelNum); return overall; } void minD(TreeNode *node, int &overall, int levelNum) { if(node == nullptr) return; levelNum++; minD(node->left, overall, levelNum); minD(node->right, overall, levelNum); if(node->left==nullptr && node->right==nullptr) overall = min(overall,levelNum); } };
//2014-2-16 update int minDepth(TreeNode *root) { if (!root) return 0; if (!root->left && !root->right) return 1; int L = root->left? minDepth(root->left)+1:INT_MAX; int R = root->right? minDepth(root->right)+1:INT_MAX; return min(L, R); }
相关文章推荐
- 【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
- [Leetcode] The minimum depth of binary tree二叉树的最小深度
- [LeetCode] Minimum Depth of Binary Tree 二叉树的最小深度
- 【LeetCode】Minimum Depth Of Binary Tree二叉树的最小深度 - Easy
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- [LeetCode] Minimum Depth of Binary Tree 二叉树最小深度
- Leetcode Minimum Depth of Binary Tree 二叉树最小深度
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- LeetCode OJ:Minimum Depth of Binary Tree(二叉树的最小深度)
- Minimum Depth of Binary Tree 二叉树最小深度
- Minimum Depth of Binary Tree(求二叉树的最小深度)
- Minimum Depth of Binary Tree -- 二叉树的最小深度 DFS 加剪枝
- LeetCode 111 Minimum Depth of Binary Tree(二叉树的最短深度)(BT、DFS)(*)
- lintcode minimum-depth-of-binary-tree 二叉树最小深度