-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathBinary_tree_Right_Side_View.cpp
More file actions
34 lines (34 loc) · 994 Bytes
/
Binary_tree_Right_Side_View.cpp
File metadata and controls
34 lines (34 loc) · 994 Bytes
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 binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode *root) {
vector<int> result;
if(!root) return result;
queue< pair<TreeNode*, int> > Q;
int curr = root->val;
int currLevel = 1;
Q.push(make_pair(root, 1));
while(!Q.empty()) {
TreeNode* node = Q.front().first;
int level = Q.front().second;
if(level > currLevel) {
result.push_back(curr);
currLevel = level;
}
curr = node->val;
Q.pop();
if(node->left) Q.push(make_pair(node->left, level + 1));
if(node->right) Q.push(make_pair(node->right, level + 1));
}
result.push_back(curr);
return result;
}
};