-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay46.java
64 lines (53 loc) · 1.54 KB
/
Day46.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* Find Bottom Left Tree Value */
import java.util.*;
public class Day46 {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
TreeNode leftmost = null;
while (!queue.isEmpty()) {
int levelSize = queue.size();
leftmost = queue.peek();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return leftmost.val;
}
public static void main(String[] args) {
/*
2
/ \
1 3
\
4
*/
TreeNode root = new TreeNode(2);
root.left = new TreeNode(1);
root.right = new TreeNode(3);
root.right.right = new TreeNode(4);
Day46 day = new Day46();
int leftmostValue = day.findBottomLeftValue(root);
System.out.println("Leftmost value in the last row: " + leftmostValue);
}
}