Find Bottom Left Tree Value
Given a binary tree, find the leftmost value in the last row of the tree.
BFS
Time Complexity
O(N)
Space Complexity
O(N)
思路
If you fully understand how bfs works, it is a really easy problem. Just add one line into the regular bfs template. if(i == 0) leftMost = cur;
The leftmost will update until the last level.
代码
public int findBottomLeftValue(TreeNode root) {
//corner case
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
TreeNode leftMost = null;
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode cur = queue.poll();
if(i == 0) leftMost = cur;
if(cur.left != null) queue.offer(cur.left);
if(cur.right != null) queue.offer(cur.right);
}
}
return leftMost.val;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。