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.
1var findBottomLeftValue = function(root) {
2 let queue = [root];
3 let node = null;
4 while (queue.length) {
5 node = queue.shift();
6 if (node.right) queue.push(node.right);
7 if (node.left) queue.push(node.left);
8 }
9 return node.val;
10};
This JavaScript solution uses an array as a queue for the BFS process, adding children right-to-left. The final node processed will be the leftmost node on the lowest 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.
1var findBottomLeftValue
This JavaScript solution sets up recursive DFS calls for traversing the tree. With each call, it tracks maximum depth, and if a new depth surpasses earlier depths, updates the leftmost value.