> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/search/level-order-traversal/binary-tree-right-side-view.md).

# Binary Tree Right Side View

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

## Thoughts

输出二叉树最右侧的一系列元素。BFS，每层把最后一个元素输出。或者先右后左的DFS配合map记录每层最先遇到的元素。

## Code

```cpp
/*
 * @lc app=leetcode id=199 lang=cpp
 *
 * [199] Binary Tree Right Side View
 */

// @lc code=start
/**
 * 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) {
         unordered_map<int, int> m;
         int d = -1;
         stack<TreeNode*> s;
         TreeNode *pre = nullptr; 
         const auto push_right = [&](TreeNode *cur) {
             while (cur != nullptr) {
                 ++d;
                 if (!m.count(d)) m[d] = cur->val;
                 s.push(cur);
                 cur = cur->right;
             }
         };
         push_right(root);
         while (!s.empty()) {
             auto t = s.top();
             if (t->left != nullptr && t->left != pre) {
                 push_right(t->left);
                 continue;
             }
             pre = t;
             --d;
             s.pop();
         }
         d = 0;
         vector<int> r;
         while (m.count(d)) {
             r.push_back(m[d++]);
         }
         return r;
    }
};
// @lc code=end


```

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int length = queue.size();
            for (int i = 0; i < length; i++) {
                TreeNode node = queue.poll();
                if (i == length - 1) {
                    res.add(node.val);
                }
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }

        return res;
    }
}
```

## Analysis

做题耗时: 6min

时间复杂度O(n)


---

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

```
GET https://hao-fu-1.gitbook.io/oj/search/level-order-traversal/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.
