-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day42.java
67 lines (51 loc) · 1.93 KB
/
Day42.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
65
66
67
/* Binary Tree Right Side View */
import java.util.*;
public class Day42 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
int rightmostValue = 0; // Initialize with a default value
for (int i = 0; i < levelSize; i++) {
TreeNode currentNode = queue.poll();
// Update the rightmost value at each level
rightmostValue = currentNode.val;
// Add the left and right child nodes to the queue
if (currentNode.left != null) {
queue.offer(currentNode.left);
}
if (currentNode.right != null) {
queue.offer(currentNode.right);
}
}
// Add the rightmost value of the current level to the result list
result.add(rightmostValue);
}
return result;
}
public static void main(String[] args) {
// Create a binary tree
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(4);
// Call rightSideView function
List<Integer> rightSideValues = rightSideView(root);
// Print the output
System.out.println("Right Side View: " + rightSideValues);
}
}