LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
2014-11-29 17:20
645 查看
要求:此题正好和Maximum Depth of Binary Tree一题是相反的,即寻找二叉树的最小的深度值:从根节点到最近的叶子节点的距离。
结题思路:和找最大距离不同之处在于:找最小距离要注意(l<r)? l+1:r+1的区别应用,因为可能存在左右子树为空的情况,此时值就为0,但显然值是不为0的(只有当二叉树为空才为0),所以,在这里注意一下即可!
代码如下:
结题思路:和找最大距离不同之处在于:找最小距离要注意(l<r)? l+1:r+1的区别应用,因为可能存在左右子树为空的情况,此时值就为0,但显然值是不为0的(只有当二叉树为空才为0),所以,在这里注意一下即可!
代码如下:
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x): val(x),left(NULL), right(NULL) {} }; int minDepth(TreeNode *root) { if (NULL == root) return 0; int l = minDepth(root->left); int r = minDepth(root->right); if (!l) return r+1; if (!r) return l+1; return (l<r)?l+1:r+1; }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- 【LeetCode】Minimum Depth Of Binary Tree二叉树的最小深度 - Easy
- [LeetCode] Minimum Depth of Binary Tree 二叉树最小深度
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
- Leetcode Minimum Depth of Binary Tree 二叉树最小深度
- LeetCode 111 Minimum Depth of Binary Tree(二叉树的最短深度)(BT、DFS)(*)
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- [LeetCode] Minimum Depth of Binary Tree 二叉树的最小深度
- 【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)
- LeetCode Minimum Depth of Binary Tree 最小深度二叉树
- [Leetcode] The minimum depth of binary tree二叉树的最小深度
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- LeetCode OJ:Minimum Depth of Binary Tree(二叉树的最小深度)
- Minimum Depth of Binary Tree 二叉树的最小深度
- 104/111 Maximum/Minimum Depth of Binary Tree(二叉树求深度)
- Leetcode 111 Minimum Depth of Binary Tree 二叉树
- Minimum Depth of Binary Tree 二叉树最小深度