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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode.tree; | |
/** | |
* Solution: Same to MaxPath. Divide and Conquer. | |
* Difference here is it only count leaf node that root.left == null && root.right == null | |
* if not, discard. So we can't return 0 when root == null. We need a larget number to make it discard. | |
* | |
* There's case root == null. return 0. If not, we could use minDepth function directly like maxPath. | |
* | |
* @author jeffwan | |
* @date Apr 14, 2014 | |
*/ | |
public class MinDepth { | |
public int minDepth(TreeNode root) { | |
if (root == null) { | |
return 0; | |
} | |
return getMin(root); | |
} | |
public int getMin(TreeNode root) { | |
if (root == null) { | |
return Integer.MAX_VALUE; | |
} | |
if (root.left == null && root.right == null) { | |
return 1; | |
} | |
return Math.min(getMin(root.left), getMin(root.right)) + 1; | |
} | |
private class TreeNode { | |
int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) {val = x; }; | |
} | |
} |
No comments:
Post a Comment