以层为单位,取每层最右(结束)处的元素。
#define SIZE 32
/**
* 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) {
if(!root)
return {};
vector<int> res;
vector<TreeNode*> Cqueue(SIZE, NULL);
int front = 0;
int rear = 1;
int layerIndex = 0;
Cqueue[front] = root;
while(front != rear){
if(front == (rear+1)%SIZE)
cout << "FULL!";
if(Cqueue[front]->left){
Cqueue[rear] = Cqueue[front]->left;
rear = (rear+1) % SIZE;
}
if(Cqueue[front]->right){
Cqueue[rear] = Cqueue[front]->right;
rear = (rear+1) % SIZE;
}
if(layerIndex == front){
res.push_back(Cqueue[layerIndex]->val);
layerIndex = (rear-1) % SIZE;
}
front = (front+1) % SIZE;
}
return res;
}
};