zoukankan      html  css  js  c++  java
  • 刷题-力扣-199. 二叉树的右视图

    199. 二叉树的右视图

    题目链接

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题目描述

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

    示例:

    输入: [1,2,3,null,5,null,4]
    输出: [1, 3, 4]
    解释:
    
       1            <---
     /   
    2     3         <---
          
      5     4       <---
    

    题目分析

    1. 根据题目描述返回二叉树的右视图
    2. 层次遍历二叉树,取二叉树每一层的最后一个节点加入到vector中
    3. 遍历结束返回该vector

    代码

    /**
     * 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> res;
            if (!root) return res;
            queue<TreeNode*> nodeListQue;
            nodeListQue.push(root);
            int nodeListQueLen;
            while (!nodeListQue.empty()) {
                nodeListQueLen = nodeListQue.size();
                while (nodeListQueLen--) {
                    if (!nodeListQueLen) res.push_back(nodeListQue.front()->val);
                    if (nodeListQue.front()->left) nodeListQue.push(nodeListQue.front()->left);
                    if (nodeListQue.front()->right) nodeListQue.push(nodeListQue.front()->right);
                    nodeListQue.pop();
                }
            }
            return res;
        }
    };
    
  • 相关阅读:
    2019-2020nowcoder牛客寒假基础2
    2019-2020nowcoder牛客寒假基础1
    CF1291
    Daily Codeforces
    2019ICPC 上海现场赛
    Codeforces Round #686 (Div. 3)
    Codeforces Round #685 (Div. 2)
    Educational Codeforces Round 98 (Rated for Div. 2)
    Codeforces Round #654 (Div. 2)
    Codeforces Round #683 (Div. 2, by Meet IT)
  • 原文地址:https://www.cnblogs.com/HanYG/p/14931158.html
Copyright © 2011-2022 走看看