[LeetCode] Minimum Depth of Binary Tree
2014-11-13 09:51
357 查看
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.
我记得有一题是叫算Max depth 的,如出一辙。思路就是拿到一颗树,分别算出他左右子树的min depth,然后返回其中最小的那个+1就行了。
但是要注意的是和max depth有区别的地方在于,要判断左右子树存不存在先,如果不存在就忽略了。
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
我记得有一题是叫算Max depth 的,如出一辙。思路就是拿到一颗树,分别算出他左右子树的min depth,然后返回其中最小的那个+1就行了。
但是要注意的是和max depth有区别的地方在于,要判断左右子树存不存在先,如果不存在就忽略了。
int minDepth(TreeNode *root) { if (!root) return 0; if (!root->left && !root->right) return 1; int leftMin = INT_MAX; int rightMin = INT_MAX; if (root->left) leftMin = minDepth(root->left); if (root->right) rightMin = minDepth(root->right); return leftMin < rightMin ? leftMin+1 : rightMin+1; }
相关文章推荐
- [面试真题] LeetCode:Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [leetcode刷题系列]Minimum Depth of Binary Tree
- LeetCode: Minimum Depth of Binary Tree
- 【leetcode】Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- leetcode--Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- LeetCode-Minimum Depth of Binary Tree
- 【LeetCode with Python】 Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- leetcode: Minimum Depth of Binary Tree
- 【leetcode】Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- LeetCode_Minimum Depth of Binary Tree
- LeetCode题目笔记(一) -- Minimum Depth Of Binary Tree
- leetcode -- Minimum Depth of Binary Tree