MrainW's Home

All things come to those who wait!

0%

LeetCode 199. Binary Tree Right Side View

Question

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

https://leetcode.com/problems/binary-tree-right-side-view

Solution

  • Solution1 – BFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
int size = q.size();
res.add(q.peek().val);
for(int i = 0; i < size; i++){
TreeNode cur = q.poll();
if(cur.right != null) q.offer(cur.right);
if(cur.left != null) q.offer(cur.left);
}
}
return res;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels