Leetcode: Minimum Depth of Binary Tree 理解分析
2014-04-16 15:27
337 查看
题目大意:给定一个二叉树,找出树的最小深度。
理解:此题与Maximum Depth of Binary Tree(http://blog.csdn.net/zhao_shanshan/article/details/23381923)相对,让你找出最小的深度,即从根节点到叶子节点的一条节点数最少的路径。
采用递归遍历,用一个全局变量count记录扫描过节点的个数,即树的深度,用一个全局变量min记录此时扫描过的最小的深度。扫描的过程中,增加剪枝:如果还未扫描的叶子节点,此时的count已经大于min,则这条路径没必要再继续走,直接返回最小值min。
实现:
理解:此题与Maximum Depth of Binary Tree(http://blog.csdn.net/zhao_shanshan/article/details/23381923)相对,让你找出最小的深度,即从根节点到叶子节点的一条节点数最少的路径。
采用递归遍历,用一个全局变量count记录扫描过节点的个数,即树的深度,用一个全局变量min记录此时扫描过的最小的深度。扫描的过程中,增加剪枝:如果还未扫描的叶子节点,此时的count已经大于min,则这条路径没必要再继续走,直接返回最小值min。
实现:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private int min = Integer.MAX_VALUE; private int count = 0; public int minDepth(TreeNode root) { if(root == null) return 0; count ++; if(count > min) return min; if(root.left == null && root.right == null) { return count; } if(root.left != null) { int res = minDepth(root.left); if(res < min) min = res; count --; } if(root.right != null) { int re = minDepth(root.right); if(re < min) min = re; count --; } return min; } }
相关文章推荐
- Leetcode: Maximum Depth of Binary Tree 理解分析
- 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
- [LeetCode] Minimum Depth of Binary Tree
- 【leetcode c++】111 Minimum Depth of Binary Tree
- LeetCode -- Maximum Depth of Binary Tree 代码分析
- [LeetCode]Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree 二叉树最小深度
- [Leetcode 104, Easy] Minimum (Maximum) 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
- Leetcode Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- [Leetcode] Maximum |Minimum Depth of Binary Tree