-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFeb_P6_RightViewOfTree.cpp
51 lines (40 loc) · 1.85 KB
/
Feb_P6_RightViewOfTree.cpp
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 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) {
vector<int>ans;
if(root==nullptr)
return ans;
queue<TreeNode*>q;
q.push(root); // Initially push the root node
q.push(nullptr); // Then push nullptr, as level=0 contains only the root node
TreeNode* curr;
while(!q.empty()){
if(q.front()!=nullptr){ // if the end of current level is not reached
curr=q.front(); // keep the current node
// push the left and right child of curr node into the queue if exists
if(curr->left) q.push(curr->left);
if(curr->right) q.push(curr->right);
q.pop(); //remove curr node from queue
}
else{ // nullptr signifies the end of the current level, so need to add the last element of this level to ans
// last element of the level = last deleted element of queue from front
ans.push_back(curr->val); // curr contains the last deleted element of queue from front
q.pop(); // remove the nullptr, as this level has been processed
//if the queue is not empty then again push nullptr to keep a tag at the end of the next level
if(!q.empty()) q.push(nullptr);
}
}
return ans;
}
};