Minimum Depth of Binary Tree - Lintcode

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 is2.

Analysis

this "simple" problem costed me some time because i am messed up with the condition when to calculate the minimum length, which should be the following and where to put the condition (postorder). Once these are gotten straight, the rest is straightforward.

    if (node.left == null && node.right == null){
        minLength = Math.min(depth + 1, minLength);
    }
public int minLength = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
    if (root == null){
        return 0;
    }

    helper(root, 0);
    return minLength;
}

public void helper(TreeNode node, int depth) {
    if (node == null) {
        return;
    }

    helper(node.left, depth + 1);
    helper(node.right, depth + 1);

    if (node.left == null && node.right == null){
        minLength = Math.min(depth + 1, minLength);
    }
}

results matching ""

    No results matching ""