Sponsored
Sponsored
Using a BFS approach, we can efficiently explore each level of the tree from top to bottom. At each level, we keep track of the first value. The leftmost value in the last row will be the first value at the deepest level, which is the last processed level in BFS.
Time Complexity: O(n), where n is the number of nodes, as each node is visited once.
Space Complexity: O(n) in the worst case, for the queue storing nodes at the deepest level.
1using System.Collections.Generic;
2public class Solution {
3 public int FindBottomLeftValue(TreeNode root) {
4 Queue<TreeNode> queue = new Queue<TreeNode>();
5 queue.Enqueue(root);
6 TreeNode node = null;
7 while (queue.Count > 0) {
8 node = queue.Dequeue();
9 if (node.right != null) queue.Enqueue(node.right);
10 if (node.left != null) queue.Enqueue(node.left);
11 }
12 return node.val;
13 }
14}
This C# solution employs a Queue for the BFS, enqueueing nodes right-to-left per level processed. Consequently, the last-node processed embodies the leftmost node at the last level.
For the DFS approach, we explore as deep as possible, preferring left subtrees over right. We track the maximum depth, updating the leftmost value encountered at each depth level. This ensures the leftmost node at the deepest level is found.
Time Complexity: O(n), as each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to recursive call stack.
1#include
This C solution implements DFS via recursion, carrying along depth and maximal depth pointers, modifying leftmost value at maximum depth, favoring left traversals first.