[LeetCode] Binary Tree Right Side View

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.

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.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<int> res;
void build(queue<TreeNode*>& q) {
if(q.empty()) return;
res.push_back(q.front()->val);
queue<TreeNode*> nq;
while(!q.empty()) {
if(q.front()->right != nullptr) nq.push(q.front()->right);
if(q.front()->left != nullptr) nq.push(q.front()->left);
q.pop();
}
build(nq);
}
public:
vector<int> rightSideView(TreeNode* root) {
if(root == nullptr) return {};
queue<TreeNode*> q;
q.push(root);
build(q);

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/12/PS/LeetCode/binary-tree-right-side-view/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.