111. Minimum Depth of Binary Tree

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.

Approach#1: recursive "BFS"

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int min = 0;
    public int minDepth(TreeNode root) {
        if(root == null)
        {
            return 0;
        }
        traverse(root, 1);
        return min;
    }

    private void traverse(TreeNode root, int depth)
    {
        if(root.left == null && root.right == null)
        {
            min = min == 0 ? depth : Math.min(min, depth);
            return;
        }
        if(depth == min)
        {
            return;
        }
        if(root.left != null)
        {
            traverse(root.left, depth+1);
        }
        if(root.right != null)
        {
            traverse(root.right, depth+1);
        }
    }
}

results matching ""

    No results matching ""