6ms Java Solution - Easy to Understand


  • 0
    A

    Perform DFS which goes down left to right through the tree. Therefore first leaf node encountered at the max depth of the tree will be the solution.

    int globalRes;
    int globalDepth = -1;
       
    public int findBottomLeftValue(TreeNode root) {
        findLeftValueUtil(root,0);
        return globalRes;
    }
    
    public void findLeftValueUtil(TreeNode node, int depth){
        if(node == null){
            return;
        }
        
        //perform DFS
        findLeftValueUtil(node.left, depth+1);
        findLeftValueUtil(node.right, depth+1);
        
        //if we are at a leaf node, update result if greater than max depth
        if(node.left == null && node.right == null){
            if(depth > globalDepth){
                globalDepth = depth;
                globalRes = node.val;
            }
        }
    }

Log in to reply
 

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