Leetcode: Minimum Depth of Binary Tree
LeetCode of Tree Binary minimum depth
2023-09-11 14:14:08 时间
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.
这道题因为不仔细的缘故两次过,与Maximum Depth of Binary Tree问题类似,区别在于这个问题中,如果一个节点左子树为空、右子树有值,则该节点的深度应取决于右子树,而不能直接取min{左,右}
Recursive:
1 public int minDepth(TreeNode root) { 2 if(root == null) 3 return 0; 4 if(root.left == null) 5 return minDepth(root.right)+1; 6 if(root.right == null) 7 return minDepth(root.left)+1; 8 return Math.min(minDepth(root.left),minDepth(root.right))+1; 9 }
Iterative:
1 public int minDepth(TreeNode root) { 2 if(root == null) 3 return 0; 4 LinkedList queue = new LinkedList(); 5 int curNum = 0; 6 int lastNum = 1; 7 int level = 1; 8 queue.offer(root); 9 while(!queue.isEmpty()) 10 { 11 TreeNode cur = queue.poll(); 12 if(cur.left==null && cur.right==null) 13 return level; 14 lastNum--; 15 if(cur.left!=null) 16 { 17 queue.offer(cur.left); 18 curNum++; 19 } 20 if(cur.right!=null) 21 { 22 queue.offer(cur.right); 23 curNum++; 24 } 25 if(lastNum==0) 26 { 27 lastNum = curNum; 28 curNum = 0; 29 level++; 30 } 31 } 32 return 0; 33 }
相关文章
- Leetcode: Subtree of Another Tree
- Leetcode: Intersection of Two Arrays II
- Leetcode: Count of Range Sum
- Leetcode: Median of Two Sorted Arrays
- LeetCode --- 58. Length of Last Word
- English Voice of <<All Of Me>>
- [LeetCode] Longest Consecutive Sequence
- [LeetCode] Minimum Depth of Binary Tree
- 【LeetCode】191. Number of 1 Bits
- Leetcode 236 Lowest Common Ancestor of a Binary Tree
- [LeetCode] 1339. Maximum Product of Splitted Binary Tree 分裂二叉树的最大乘积
- [LeetCode] 1254. Number of Closed Islands 统计封闭岛屿的数目
- [LeetCode] 1071. Greatest Common Divisor of Strings 字符串的最大公因子
- [LeetCode] 883. Projection Area of 3D Shapes 三维物体的投影面积
- [LeetCode] 856. Score of Parentheses 括号的分数
- [LeetCode] 694. Number of Distinct Islands 不同岛屿的个数
- [LeetCode] Design In-Memory File System 设计内存文件系统
- [LeetCode] Find Leaves of Binary Tree 找二叉树的叶节点
- [LeetCode] Power of Three 判断3的次方数
- [LeetCode] 236. Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点
- [LeetCode] 17. Letter Combinations of a Phone Number 电话号码的字母组合
- Leetcode——17. Letter Combinations of a Phone Number
- leetcode 191. Number of 1 Bits 位1的个数(简单)