二叉树右视图

GitHub跳转原题关系图返回列表

BFS 每层最后一个,或 DFS 先右后左首次到达深度时记录。

OJ: leetcodecn

题目 ID: binary-tree-right-side-view

难度:普及+/提高

标签:二叉树BFSDFScpppython

日期: 2026-07-29 13:10

题意

返回二叉树从右侧看到的节点值。

思路

BFS 层序遍历取每层最后一个。DFS 先右后左,首次到达某深度时记录。

代码

cpp
#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left, *right;

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
    vector<int> rightSideView(TreeNode *root) {
        if (!root)
            return {};
        vector<int> ans;
        queue<TreeNode *> q;
        q.push(root);
        while (!q.empty()) {
            for (int sz = q.size(); sz--; q.pop()) {
                auto cur = q.front();
                if (sz == 0)
                    ans.push_back(cur->val);
                if (cur->left)
                    q.push(cur->left);
                if (cur->right)
                    q.push(cur->right);
            }
        }
        return ans;
    }
};

TreeNode *build(istream &in, int n) {
    if (!n)
        return nullptr;
    vector<TreeNode *> nodes(n);
    queue<TreeNode *> q;
    for (int i = 0, v; i < n; i++) {
        in >> v;
        if (v != -1)
            nodes[i] = new TreeNode(v);
    }
    TreeNode *root = nodes[0];
    if (root)
        q.push(root);
    int idx = 1;
    while (!q.empty() && idx < n) {
        auto cur = q.front();
        q.pop();
        if (idx < n) {
            cur->left = nodes[idx];
            if (nodes[idx])
                q.push(nodes[idx]);
            idx++;
        }
        if (idx < n) {
            cur->right = nodes[idx];
            if (nodes[idx])
                q.push(nodes[idx]);
            idx++;
        }
    }
    return root;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    auto r = build(cin, n);
    for (int x : Solution().rightSideView(r))
        cout << x << ' ';
    return 0;
}
python
#!/usr/bin/env python3
from collections import deque
from typing import List, Optional


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = self.right = None


class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        ans, q = [], deque([root])
        while q:
            for i in range(len(q)):
                cur = q.popleft()
                if i == 0:
                    ans.append(cur.val)
                if cur.right:
                    q.append(cur.right)
                if cur.left:
                    q.append(cur.left)
        return ans


def build(arr):
    if not arr:
        return None
    nodes = [TreeNode(v) if v != -1 else None for v in arr]
    q = deque([nodes[0]]) if nodes[0] else deque()
    idx = 1
    while q and idx < len(arr):
        cur = q.popleft()
        if idx < len(arr):
            cur.left = nodes[idx]
            if nodes[idx]:
                q.append(nodes[idx])
            idx += 1
        if idx < len(arr):
            cur.right = nodes[idx]
            if nodes[idx]:
                q.append(nodes[idx])
            idx += 1
    return nodes[0]


def main():
    n = int(input())
    a = list(map(int, input().split()))
    print(*Solution().rightSideView(build(a)))


if __name__ == "__main__":
    main()

复杂度

时间 O(n),空间 O(n)。

总结

右视图本质是"每层最右侧节点"。