Monday, April 14, 2014

Minimum Depth of Binary Tree @LeetCode

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.

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; };
}
}
view raw MinDepth.java hosted with ❤ by GitHub

No comments:

Post a Comment