-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find_the_bottom_left_Tree_value.java
41 lines (37 loc) · 1.13 KB
/
Find_the_bottom_left_Tree_value.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//Given a binary tree, find the leftmost value in the last row of the tree.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
// Use a BFS approach to solve this problem. If the queue is empty, return left.
// Else BFS traverse the remaining part.
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int left = root.val;
while(!q.isEmpty())
{
int size = q.size();
for (int i=0;i<size;i++)
{
// Remove the node from teh queue.
TreeNode temp = q.poll();
if(i==0){
// This would be the leftmost node, hence assign this to left.
left = temp.val;
}
if(temp.left!=null)
q.add(temp.left);
if(temp.right!=null)
q.add(temp.right);
}
}
return left;
}
}