LeetCode.199.二叉树的右视图

题目

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

简而言之就是取每层右边的第一个节点

对比上一题就是取本层的最后一个节点,在for循环遍历中少遍历一次即可提取

cpp 复制代码
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        queue<TreeNode*> que;
        vector<int> result;
        if (root != NULL) que.push(root);
        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size - 1; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
            TreeNode* node = que.front();
            que.pop();
            if (node->left) que.push(node->left);
            if (node->right) que.push(node->right);
            result.push_back(node -> val); 
        }
        return result;
    }
};
相关推荐
Navigator_Z12 小时前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
星恒随风1 天前
从0实现C++ AI大模型接入SDK(四):大模型API接入、公共数据结构设计与日志库封装
linux·服务器·数据结构·c++·人工智能
wy_hhxx1 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK1 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
饮水桶_T1 天前
HashMap笔记
开发语言·数据结构·笔记
风落青芜1 天前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z1 天前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah1 天前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
凌冰_2 天前
数据结构 - 渐进符号和递归的复杂度(二)
数据结构·算法·软件工程
Navigator_Z2 天前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode