Advertisement

Find Bottom Left Tree Value - LeetCode 513 Solution

Find Bottom Left Tree Value - Complete Solution Guide

Find Bottom Left Tree Value is LeetCode problem 513, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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 Constraints: The number of nodes in the tree is in the range [1, 10 4 ] . -2 31 <= Node.val <= 2 31 - 1

Detailed Explanation

The problem asks us to find the value of the leftmost node in the last (deepest) row of a given binary tree. The input is the root node of the tree, and the output is a single integer representing the value of the leftmost node in the bottom row.

Solution Approach

The solution utilizes Breadth-First Search (BFS) to traverse the binary tree level by level. The key idea is to add the right child to the queue *before* adding the left child. This ensures that when processing each level, we are moving from right to left. As a result, the last node we encounter (and the last one left in the queue) will be the leftmost node in the bottommost row of the tree. We keep updating `current_node` variable for each node visited by the BFS algorithm. Finally, the `current_node.val` stores the value of the leftmost node in the last row.

Step-by-Step Algorithm

  1. Step 1: Initialize a queue with the root node.
  2. Step 2: Initialize a variable `current_node` to store the last visited node; initially, it's set to the root.
  3. Step 3: While the queue is not empty, dequeue a node from the queue and update the `current_node` to the value of the dequeued node.
  4. Step 4: Enqueue the right child of the dequeued node (if it exists).
  5. Step 5: Enqueue the left child of the dequeued node (if it exists).
  6. Step 6: Repeat steps 3-5 until the queue is empty.
  7. Step 7: Return the value of the `current_node` because after all the nodes are visted it contains the last visited node which is the left most node in last level

Key Insights

  • Insight 1: Breadth-First Search (BFS) is well-suited for traversing a tree level by level, making it easy to identify the last row.
  • Insight 2: By processing the right child before the left child in the BFS, the last node processed in the queue will always be the leftmost node of the last level.
  • Insight 3: We don't need to explicitly track the level depth. Since BFS processes level by level, the last node we dequeue is guaranteed to be the leftmost node in the last row.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(w)

Topics

This problem involves: Tree, Depth-First Search, Breadth-First Search, Binary Tree.

Companies

Asked at: josh technology.