Binary Tree Right Side View LeetCode solution in Java

1
class Solution {
2
// Utility Function of RightSideView
3
public void rightView(TreeNode curr, List<Integer> list, int level) {
4
// if, current is null, return
5
if (curr == null) {
6
return;
7
}
8

9
// if, level = list size
10
// add current val to list
11
if (level == list.size()) {
12
list.add(curr.val);
13
}
14

15
// recursive call for right side view
16
rightView(curr.right, list, level + 1);
17
// recursive call for left side view
18
rightView(curr.left, list, level + 1);
19
}
20

21
// Binary Tree Right Side View Function
22
public List<Integer> rightSideView(TreeNode root) {
23
// create a list
24
List<Integer> result = new ArrayList<>();
25
// call right view function
26
rightView(root, result, 0);
27
return result;
28
}
29
}
30

31
// Output -
32
/*
33
Input: root = [1,2,3,null,5,null,4]
34
Output: [1,3,4]
35
*/
36

37
// Time & Space Complexity -
38
/*
39
Time - O(n)
40
Space - O(h) h = height of binary tree
41
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0