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

# 199 Binary Tree Right Side View

Given a binary tree, imagine yourself standing on therightside of it, return the values of the nodes you can see ordered from top to bottom.

For example:\
Given the following binary tree,

```
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
```

You should return`[1, 3, 4]`.

**The Idea:** Run a level order traversal. Append null if you reach null as an indicator for the next level. It then follows that if the next element in the queue is null, we are on the right side of the tree.

**Complexity:** O(n) time and space

```cpp
vector<int> rightSideView(TreeNode* root) {
    vector<int> right_side;
    if (!root) return right_side;

    queue<TreeNode*> q;
    q.push(root);
    q.push(nullptr);

    while (!q.empty()) {
        TreeNode *front = q.front(); q.pop();
        if (front) {
            if (front->left) q.push(front->left);
            if (front->right) q.push(front->right);
            if (!q.front())
                right_side.push_back(front->val);
        }
        else if (!front && !q.empty()) {
            q.push(nullptr);
        }
    }

    return right_side;
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/199-binary-tree-right-side-view.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
