199.二叉树的右视图(BFS)

给定一个二叉树的根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例 1:

输入: [1,2,3,null,5,null,4]

输出: [1,3,4]

示例 2:

输入: [1,null,3]

输出: [1,3]

示例 3:

输入: []

输出: []

解题思路

本文使用Bfs思想,层序遍历,只保留最后一个结点的值。

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {

public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> result; // 存储每一层最后一个节点的值
        queue<TreeNode*> nodeQueue; // 队列用于BFS

        if (root == nullptr)
            return result;

        nodeQueue.push(root);      // 将根节点放入队列
        int currentLevelNodes = 1; // 当前层剩余要处理的节点数
        int nextLevelNodes = 0;    // 下一层的节点数

        while (!nodeQueue.empty()) {
            TreeNode* currentNode = nodeQueue.front();
            nodeQueue.pop();
            --currentLevelNodes; // 处理一个节点,当前层节点数减一

            if (currentNode->left != nullptr) {
                nodeQueue.push(currentNode->left);
                ++nextLevelNodes; // 下一层节点数加一
            }
            if (currentNode->right != nullptr) {
                nodeQueue.push(currentNode->right);
                ++nextLevelNodes; // 下一层节点数加一
            }

            // 如果当前层的节点已经全部处理完,则把当前节点的值添加到结果中,
            // 并重置当前层节点数为下一层的节点数
            if (currentLevelNodes == 0) {
                result.push_back(currentNode->val);
                currentLevelNodes = nextLevelNodes;
                nextLevelNodes = 0;
            }
        }

        return result;
    }
};
相关推荐
MobotStone1 天前
一夜蒸发1000亿美元后,Google用什么夺回AI王座
算法
Wang201220131 天前
RNN和LSTM对比
人工智能·算法·架构
xueyongfu1 天前
从Diffusion到VLA pi0(π0)
人工智能·算法·stable diffusion
永远睡不够的入1 天前
快排(非递归)和归并的实现
数据结构·算法·深度优先
cheems95271 天前
二叉树深搜算法练习(一)
数据结构·算法
sin_hielo1 天前
leetcode 3074
数据结构·算法·leetcode
Yzzz-F1 天前
算法竞赛进阶指南 动态规划 背包
算法·动态规划
程序员-King.1 天前
day124—二分查找—最小化数组中的最大值(LeetCode-2439)
算法·leetcode·二分查找
predawnlove1 天前
【NCCL】4 AllGather-PAT算法
算法·gpu·nccl
驱动探索者1 天前
[缩略语大全]之[内存管理]篇
java·网络·算法·内存管理