https://leetcode.com/problems/binary-tree-right-side-view/description/?envType=study-plan-v2&envId=top-interview-150
Algorithm
rightside.nextLevel queue.nextLevel queue is not empty:
currLevel = nextLevel, and empty the next level nextLevel.nextLevel queue.currLevel is empty, and the node we have in hands is the last one, and makes a part of the right side view. Add it into rightside.rightside./**
* 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 {
public:
vector<int> rightSideView(TreeNode* root) {
if (root == nullptr) return vector<int>();
deque<TreeNode*> nextLevel{root};
deque<TreeNode*> currLevel;
vector<int> rightside;
TreeNode* node = nullptr;
while (!nextLevel.empty()){
currLevel = nextLevel;
nextLevel.clear();
while (!currLevel.empty()){
node = currLevel.front();
currLevel.pop_front();
if (node->left != nullptr) nextLevel.push_back(node->left);
if (node->right != nullptr) nextLevel.push_back(node->right);
}
rightside.push_back(node->val);
}
return rightside;
}
};
Complexity Analysis
Algorithm
rightside.null sentinel to mark the end of the first level.root.prev = curr and pop the current node from the queue curr = queue.poll().null:
prev = curr, curr = queue.poll().rightside.rightside./**
* 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 {
public:
vector<int> rightSideView(TreeNode* root) {
if (root == NULL) return vector<int>();
queue<TreeNode*> queue;
queue.push(root);
queue.push(NULL);
TreeNode *prev, *curr = root;
vector<int> rightside;
while (!queue.empty()){
prev = curr;
curr = queue.front();
queue.pop();
while (curr != NULL){
// add child nodes in the queue
if(curr->left != NULL){
queue.push(curr->left);
}
if(curr->right != NULL){
queue.push(curr->right);
}
prev = curr;
curr = queue.front();
queue.pop();
}
// the current level is finished
// and prev is the rightmost element
rightside.push_back(prev->val);
// add a sentinel to mark the end
// of the next level
if (!queue.empty()) queue.push(NULL);
}
return rightside;
}
};
Complexity Analysis