Find Bottom Left Tree Value

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

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2:

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Note: You may assume the tree (i.e., the given root node) is not NULL.

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int ans = -1;
        while (q.size() != 0) {
            int size = q.size();
            int element = 0;
            boolean firstElement = true;
            while (size-- > 0) {
                TreeNode node = q.poll();
                if (firstElement) {
                    firstElement = false;
                    element = node.val;
                }
                if (node.left != null)
                    q.add(node.left);
                if (node.right != null) 
                    q.add(node.right);
            }
            if (q.size() == 0)
                ans = element;
        }
        return ans;
    }
}

Last updated