Java DFS solution, Recursive


  • 0
    C
    public class Solution {
    public int minDepth(TreeNode root) {
        if(null == root) return 0;
        int currentDepth = 0, min = Integer.MAX_VALUE;
        return depthFirstSearch(root, currentDepth, min);
    }
    
    private int depthFirstSearch(TreeNode node, int currentDepth, int min){
    	currentDepth += 1;
    	if(currentDepth > min) return min;
    	//if leaf
    	if(null == node.left && null == node.right)
    		return currentDepth < min ? currentDepth : min;
    	if(null != node.left){
    		min = Math.min(min, depthFirstSearch(node.left, currentDepth, min));
    	}
    	if(null != node.right){
    		min = Math.min(min, depthFirstSearch(node.right, currentDepth, min));
    	}
    	return min;
    }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.