# 199. Binary Tree Right Side View (Medium)

## 1.問題

* 回傳每一層的最右邊元素

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LIF1R2AIAsSOzkYqZMI%2F-LIKSaS1m8VqkGq_EukT%2F2018072605.jpg?alt=media\&token=22a43201-8b19-4846-8ded-8d926fe38db2)

## 2.想法

* 用level-order traversal, 並且把每一層的最後一個元素放到vector中

## 3.程式碼

```
/**
 * 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> v;
    if (!root) {
        return v;
    }
    queue<TreeNode*> q;
    q.push(root);

    v.push_back(root->val);
    while (!q.empty()) { 
        int size = q.size();
        int tmp = 0;
        int flag = 0;
        for(int i = 0; i < size; i++) {
            TreeNode* node = q.front(); 
            q.pop(); 
            if (node->left) {
                q.push(node->left);
                tmp = node->left->val;
                flag = 1;
            }
            if (node->right) {
                q.push(node->right);
                tmp = node->right->val;
                flag = 1;
            }
        }
        if (flag){
            v.push_back(tmp);
        }
    }
    return v;
}
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LIF1R2AIAsSOzkYqZMI%2F-LIKUGisBwX4KQInJ9Vo%2F2018072606.jpg?alt=media\&token=216e230e-6b5b-4a84-bfcc-a21a5fcd37bd)
