LeetCode Solutions

513. Find Bottom Left Tree Value

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  int findBottomLeftValue(TreeNode* root) {
    queue<TreeNode*> q{{root}};
    TreeNode* node = nullptr;

    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;
  }
};
			

class Solution {
  public int findBottomLeftValue(TreeNode root) {
    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));
    TreeNode node = null;

    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;
  }
}
			

class Solution:
  def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
    q = deque([root])

    while q:
      root = q.popleft()
      if root.right:
        q.append(root.right)
      if root.left:
        q.append(root.left)

    return root.val