Find Bottom Left Tree Value

medium tree bfs

Problem

Given the root of a binary tree, return the leftmost value in the last row (deepest level).

Inputtree = [2, 1, 3, 4, null, 5, 6, 7]
Output7
Deepest level holds only node 7.

from collections import deque

def find_bottom_left_value(root):
    q = deque([root])
    node = root
    while q:
        node = q.popleft()
        if node.right:
            q.append(node.right)
        if node.left:
            q.append(node.left)
    return node.val
function findBottomLeftValue(root) {
  const q = [root];
  let node = root;
  while (q.length) {
    node = q.shift();
    if (node.right) q.push(node.right);
    if (node.left) q.push(node.left);
  }
  return node.val;
}
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Deque<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        TreeNode node = root;
        while (!q.isEmpty()) {
            node = q.poll();
            if (node.right != null) q.offer(node.right);
            if (node.left != null) q.offer(node.left);
        }
        return node.val;
    }
}
int findBottomLeftValue(TreeNode* root) {
    queue<TreeNode*> q;
    q.push(root);
    TreeNode* node = root;
    while (!q.empty()) {
        node = q.front(); q.pop();
        if (node->right) q.push(node->right);
        if (node->left) q.push(node->left);
    }
    return node->val;
}
Time: O(n) Space: O(w)