Skip to content

Commit 7530882

Browse files
committed
added dsa code for binary tree right side view
1 parent 5e9d9f7 commit 7530882

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.thealgorithms.datastructures;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedList;
5+
import java.util.List;
6+
import java.util.Queue;
7+
8+
public class BinaryTreeRightSideView {
9+
10+
// FIX: Make the TreeNode class static.
11+
static class TreeNode {
12+
int val;
13+
TreeNode left, right;
14+
TreeNode(int x) {
15+
this.val = x;
16+
}
17+
}
18+
19+
// FIX: Make the RightSideView class static.
20+
public static class RightSideView {
21+
public List<Integer> rightSideView(TreeNode root) {
22+
List<Integer> result = new ArrayList<>();
23+
if (root == null) {
24+
return result;
25+
}
26+
27+
Queue<TreeNode> queue = new LinkedList<>();
28+
queue.add(root);
29+
30+
while (!queue.isEmpty()) {
31+
int size = queue.size();
32+
for (int i = 0; i < size; i++) {
33+
TreeNode node = queue.poll();
34+
35+
// If it's the last node in this level, add it to the result.
36+
if (i == size - 1) {
37+
result.add(node.val);
38+
}
39+
40+
if (node.left != null) {
41+
queue.add(node.left);
42+
}
43+
if (node.right != null) {
44+
queue.add(node.right);
45+
}
46+
}
47+
}
48+
return result;
49+
}
50+
51+
// The main method can now correctly instantiate these static classes.
52+
public static void main(String[] args) {
53+
RightSideView sol = new RightSideView();
54+
55+
TreeNode root = new TreeNode(1);
56+
root.left = new TreeNode(2);
57+
root.right = new TreeNode(3);
58+
root.left.right = new TreeNode(5);
59+
root.right.right = new TreeNode(4);
60+
61+
// The logic correctly produces the right side view.
62+
System.out.println(sol.rightSideView(root)); // Expected Output: [1, 3, 4]
63+
}
64+
}
65+
}

0 commit comments

Comments
 (0)