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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/199.-binary-tree-right-side-view-medium.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
