199. 二叉树的右视图

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

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

示例 2:

输入: [1,null,3]
输出: [1,3]

示例 3:

输入: []
输出: []

这道题就是老生常谈的问题了

依旧是二叉树的层次遍历,只需要在每次遍历队列过程中,取出队尾元素即可!

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res ;
         if(root == nullptr) return res ;
         queue<TreeNode*> q ;
         q.push(root) ;
         while(!q.empty()){
             auto end = q.back() ;
             res.push_back(end -> val) ;
             for(int i = q.size() ; i ; i --){
                 auto begin = q.front() ;
                 q.pop() ;
                 if(begin -> left != nullptr ) q.push(begin -> left) ;
                 if(begin -> right != nullptr) q.push(begin -> right) ;
             }
         }
         return res ;
    }
};
posted @ 2022-01-23 20:35  爪洼ing  阅读(25)  评论(0编辑  收藏  举报