Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.thealgorithms.datastructures.trees;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
* Given the root of a binary tree, returns the values of the nodes visible
* from the right side (the last node of each level in a level-order traversal).
*
* <p>Example:
* <pre>
* 1
* / \
* 2 3
* \ \
* 5 4
* Right side view: [1, 3, 4]
* </pre>
*
* <p>Time complexity: O(n), Space complexity: O(n)
*
* @see <a href="https://leetcode.com/problems/binary-tree-right-side-view/">LeetCode #199</a>
*/
public final class RightSideViewOfBinaryTree {
private RightSideViewOfBinaryTree() {
}

public static List<Integer> rightSideView(BinaryTree.Node root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}

Queue<BinaryTree.Node> queue = new LinkedList<>();
queue.add(root);

while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
BinaryTree.Node node = queue.poll();
if (i == levelSize - 1) {
result.add(node.data);
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
return result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.thealgorithms.datastructures.trees;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;

public class RightSideViewOfBinaryTreeTest {

@Test
public void testNullRoot() {
assertEquals(Collections.emptyList(), RightSideViewOfBinaryTree.rightSideView(null));
}

@Test
public void testSingleNode() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1});
assertEquals(List.of(1), RightSideViewOfBinaryTree.rightSideView(root));
}

/*
1
/ \
2 3
\ \
5 4
*/
@Test
public void testRightSideView() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, null, 5, null, 4});
assertEquals(List.of(1, 3, 4), RightSideViewOfBinaryTree.rightSideView(root));
}

/*
1
/
2
/
3
*/
@Test
public void testLeftSkewedTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, null, 3});
assertEquals(List.of(1, 2, 3), RightSideViewOfBinaryTree.rightSideView(root));
}

/*
1
\
2
\
3
*/
@Test
public void testRightSkewedTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, null, 2, null, 3});
assertEquals(List.of(1, 2, 3), RightSideViewOfBinaryTree.rightSideView(root));
}
}
Loading