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.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The minimum depth is 2.
思路
- 此題的思路與maximum depth很類似件已,但是由于求的是minDepth讲婚,所以如果左右子樹(shù)中有一個(gè)為空會(huì)返回0渐逃,這時(shí)我們是不能算做有效深度的遵馆。
-
所以分成了三種情況
1)左子樹(shù)為空: 返回右子樹(shù)depth + 1;
2)右子樹(shù)為空: 返回左子樹(shù)depth + 1;
3)左右子樹(shù)都不為空:返回Math.min(helper(root.left), helper(root.right)) + 1;
。
4) 當(dāng)然肉瓦,如果左右子樹(shù)都為空的話琉苇,就會(huì)返回1狰腌。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: The root of binary tree
* @return: An integer
*/
private int min = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
// write your code here
if (root == null) {
return 0;
}
int result = helper(root);
return result;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null) {
return helper(root.right) + 1;
}
if (root.right == null) {
return helper(root.left) + 1;
}
// right, left are not null
return Math.min(helper(root.left), helper(root.right)) + 1;
}
}