-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path199. Binary Tree Right Side View.cpp
More file actions
39 lines (39 loc) · 1015 Bytes
/
199. Binary Tree Right Side View.cpp
File metadata and controls
39 lines (39 loc) · 1015 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
35
36
37
38
39
/**
* Definition for a binary tree node.
* 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> res;
if(!root) return res;
int curLevelCnt = 1, nextLevelCnt = 0, visitedCnt = 0;
queue<TreeNode*> q;
q.push(root);
TreeNode* cur;
while(!q.empty()){
cur = q.front(), q.pop();
visitedCnt++;
if(cur->left){
nextLevelCnt++;
q.push(cur->left);
}
if(cur->right){
nextLevelCnt++;
q.push(cur->right);
}
if(curLevelCnt == visitedCnt){
res.push_back(cur->val);
curLevelCnt = nextLevelCnt;
nextLevelCnt = 0;
visitedCnt= 0;
}
}
return res;
}
};