[LeetCode] Find Bottom Left Tree Value
文章目录
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;
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论