# 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: 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://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/199-binary-tree-right-side-view.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.
