[LeetCode]Minimum Depth of Binary Tree
2016-11-17 17:18
288 查看
Question
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.
本题难度Easy。
递归
【复杂度】
时间 O(N) 空间 O(N)
【思路】
当求最大深度时,我们只要在左右子树中取较大的就行了,然而最小深度时,如果左右子树中有一个为空会返回0,这时我们是不能算做有效深度的。所以分成了三种情况,左子树为空,右子树为空,左右子树都不为空。当然,如果左右子树都为空的话,就会返回1。
【代码】
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.
本题难度Easy。
递归
【复杂度】
时间 O(N) 空间 O(N)
【思路】
当求最大深度时,我们只要在左右子树中取较大的就行了,然而最小深度时,如果左右子树中有一个为空会返回0,这时我们是不能算做有效深度的。所以分成了三种情况,左子树为空,右子树为空,左右子树都不为空。当然,如果左右子树都为空的话,就会返回1。
【代码】
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int minDepth(TreeNode root) { //base case if(root==null){ return 0; } //invariant int left=minDepth(root.left); int right=minDepth(root.right); //ensure if(left==0&&right==0) return 1; else if(left==0&&right>0) return right+1; else if(right==0&&left>0) return left+1; else return Math.min(left,right)+1; } }
参考
[Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度相关文章推荐
- 92_leetcode_Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- 【LeetCode从零单刷】Minimum Depth of Binary Tree
- leetcode111---Minimum Depth of Binary Tree
- LeetCode题目笔记(一) -- Minimum Depth Of Binary Tree
- LeetCode-Maximum/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 C++
- [LeetCode]Minimum Depth of Binary Tree
- leetcode-111 Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree LeetCode
- 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:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- leetcode - Minimum Depth of Binary Tree