Easy Java solution using level order traversal


  • 0
    D
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int findBottomLeftValue(TreeNode root) {
            
         //variable to store the answer
         ArrayList<ArrayList<Integer>> solution=new ArrayList<ArrayList<Integer>>();
         
         //recursive function to find all levels in the tree
         levelOrder(0,root,solution);
            
        //the leftmost element of the last level is the bottom left tree value
         int len=solution.size();
            
         return solution.get(len-1).get(0);   
            
        }
        
        public void levelOrder(int level,TreeNode root,ArrayList<ArrayList<Integer>> solution)
        {
            //Base case: if root is null, return
            if(root==null)
                return;
            
            //General case:if root is present, add it to solution and then recurse on left and right subtrees
            //Case 1: level already present in solution
            if(level<solution.size())
                solution.get(level).add(root.val);
            //Case 2: new level needs to be added to the solution
            else
            {
                ArrayList<Integer> list=new ArrayList<Integer>();
                list.add(root.val);
                solution.add(list);
            }
            
            //recurse on left and right subtrees
            levelOrder(level+1,root.left,solution);
            
            levelOrder(level+1,root.right,solution);
        }
    }
    

Log in to reply
 

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