Return the leftmost value in the last row of the tree.
Example 1:
Input: root = [2,1,3]
Output: 1
Explanation: The last row is [1,3], so the leftmost value is 1.
Example 2:
Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7
Explanation: The last row contains only the node 7.
Constraints:
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 - 1
Solutions
Solution 1
Thinking
The bottom-left value is the first node of the last level in a level-order walk. In BFS the queue front is the leftmost node of the current level.
Record the front at the start of each level and enqueue children. When the queue drains, the last recorded value is the answer. Level order processes the deepest level last.
1 2 3 4 5 6 7 8 910111213141516171819
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:deffindBottomLeftValue(self,root:Optional[TreeNode])->int:q=deque([root])ans=0whileq:ans=q[0].valfor_inrange(len(q)):node=q.popleft()ifnode.left:q.append(node.left)ifnode.right:q.append(node.right)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindBottomLeftValue(root*TreeNode)int{q:=[]*TreeNode{root}ans:=0forlen(q)>0{ans=q[0].Valfori:=len(q);i>0;i--{node:=q[0]q=q[1:]ifnode.Left!=nil{q=append(q,node.Left)}ifnode.Right!=nil{q=append(q,node.Right)}}}returnans}
BFS uses an \(O(w)\) queue. DFS only needs to remember the first time a greater depth appears.
A left-then-right preorder meets the leftmost node of each depth first; update the answer only when the depth is strictly larger. Extra space is the recursion stack, and the result matches level order.
1 2 3 4 5 6 7 8 9101112131415161718192021
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:deffindBottomLeftValue(self,root:Optional[TreeNode])->int:defdfs(root,curr):ifrootisNone:returndfs(root.left,curr+1)dfs(root.right,curr+1)nonlocalans,mxifmx<curr:mx=currans=root.valans=mx=0dfs(root,1)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindBottomLeftValue(root*TreeNode)int{ans,mx:=0,0vardfsfunc(*TreeNode,int)dfs=func(root*TreeNode,currint){ifroot==nil{return}dfs(root.Left,curr+1)dfs(root.Right,curr+1)ifmx<curr{mx=currans=root.Val}}dfs(root,1)returnans}