> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/199.-binary-tree-right-side-view-medium.md).

# 199. Binary Tree Right Side View (Medium)

## 1.問題

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

![](/files/-LIKSaS1m8VqkGq_EukT)

## 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

![](/files/-LIKUGisBwX4KQInJ9Vo)
