199. Binary Tree Right Side View

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.

BFS搜索。层级遍历各个节点,当节点为该层级最后一个节点时,将其值加入返回列表。

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if(root == null) return ret;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int size = 1;
while(!q.isEmpty()){
for(int i = 0; i < size; i++){
TreeNode curr = q.poll();
if(i == size - 1) ret.add(curr.val);
if(curr.left != null) q.add(curr.left);
if(curr.right != null) q.add(curr.right);
}
size = q.size();
}
return ret;
}
}
Author

Xander

Posted on

2022-05-02

Updated on

2022-05-01

Licensed under

Comments