zoukankan      html  css  js  c++  java
  • 199. Binary Tree Right Side View

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

    For example:
    Given the following binary tree,

       1            <---
     /   
    2     3         <---
          
      5     4       <---
    

    You should return [1, 3, 4].

    ==============

    利用BFS遍历二叉树的方法,

    queue<TreeNode*> q;

    curr/next分别记录当前层要遍历的节点数量,下层要遍历的节点数量

    ====

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        ///
        vector<int> rightSideView(TreeNode* root) {
            vector<int> re;
            if(root==nullptr) return re;
            help_rightSv(root,re);
    
            for(auto i:re){
                cout<<i<<" ";
            }cout<<endl;
            return re;
        }
    
        void help_rightSv(TreeNode *root,vector<int> &path){
            queue<TreeNode*> q;
            int curr = 1;
            int next = 0;
            int level = 0;
            q.push(root);
            while(!q.empty()){
                if(curr>0){
                    TreeNode *tmp = q.front();
                    if(path.size()==level) {
                        path.push_back(tmp->val);
                    }
                    q.pop();
                    curr--;
                    if(tmp->right!=nullptr){
                        q.push(tmp->right);
                        next++;
                    }
                    if(tmp->left!=nullptr){
                        q.push(tmp->left);
                        next++;
                    }
                }else{
                    curr = next;
                    next = 0;
                    level++;
                }
            }///while
        }
    };
  • 相关阅读:
    【JOI2017春季合宿】Port Facility
    LOJ504「LibreOJ β Round」ZQC 的手办
    UOJ37. 【清华集训2014】主旋律
    CF1012F Passports
    AT2370 Piling Up
    CF908G New Year and Original Order
    CF643E Bear and Destroying Subtrees
    CF183D T-shirt
    「JOISC 2016 Day 3」回转寿司
    「LibreOJ β Round #2」计算几何瞎暴力
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5618745.html
Copyright © 2011-2022 走看看