LeetCode 41 Minimum Depth of Binary Tree
2014-08-30 18:27
369 查看
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 nearest leaf node.
分析:
二叉树用递归。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
int lMin = minDepth(root.left);
int rMin = minDepth(root.right);
if(lMin==0 && rMin==0) return 1;
//下面这两行是避免把只有一个孩子的中间节点当成叶子节点
if(lMin == 0) lMin = Integer.MAX_VALUE;
if(rMin == 0) rMin = Integer.MAX_VALUE;
return Math.min(lMin, rMin) + 1;
}
}
The minimum depth is the number of nodes along the shortest path from the root node down to nearest leaf node.
分析:
二叉树用递归。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
int lMin = minDepth(root.left);
int rMin = minDepth(root.right);
if(lMin==0 && rMin==0) return 1;
//下面这两行是避免把只有一个孩子的中间节点当成叶子节点
if(lMin == 0) lMin = Integer.MAX_VALUE;
if(rMin == 0) rMin = Integer.MAX_VALUE;
return Math.min(lMin, rMin) + 1;
}
}
相关文章推荐
- [面试真题] 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】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】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