Find Bottom Left Tree Value

 Given the root of a binary tree, return the leftmost value in the last row of the tree.


 


Example 1:



Input: root = [2,1,3]

Output: 1

Example 2:



Input: root = [1,2,3,4,null,5,6,null,null,7]

Output: 7

 /**

 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int findBottomLeftValue(TreeNode root) {
       

         Queue<TreeNode> q = new LinkedList<>();
         q.offer(root);

         int leftMost=root.val;

         while(!q.isEmpty())
         {
            int size=q.size();
           
            leftMost=q.peek().val;

            for(int i=0;i<size;i++)
            {
               TreeNode curr = q.poll();

                if(curr.left !=null)
                {
                    q.offer(curr.left);
                }
                   if(curr.right !=null)
                {
                    q.offer(curr.right);
                }
            }
           
         }

         return leftMost;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence