zoukankan      html  css  js  c++  java
  • 二叉树的右视图

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

    示例:

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

    1 <---
    /
    2 3 <---

    5 4 <---

    code:bfs

    /**
     * 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) {
            if(root==nullptr)
                return {};
            
            vector<int> res;
            queue<TreeNode*> q;
            q.push(root);
            TreeNode* last=root,*nlast=nullptr;
            while(!q.empty())
            {
                root=q.front();
                q.pop();
                if(root->left)
                {
                    q.push(root->left);
                    nlast=root->left;
                }
                if(root->right)
                {
                    q.push(root->right);
                    nlast=root->right;
                }
                if(root==last)
                {
                    res.push_back(root->val);
                    last=nlast;
                }
            }
            return res;
        }
    };

     code:递归,根,右,左,当当前深度比最大深度大时,放入结果集

    /**
     * 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 {
    private:
        void rightSideViewCore(TreeNode* root,vector<int>& res,int deep,int& maxDeep)
        {
            if(root==nullptr)
                return ;
    
            if(deep>maxDeep)
            {
                maxDeep=deep;
                res.push_back(root->val);
            }
            rightSideViewCore(root->right,res,deep+1,maxDeep);
            rightSideViewCore(root->left,res,deep+1,maxDeep);
        }
    public:
        vector<int> rightSideView(TreeNode* root) {
            if(root==nullptr)
                return {};
            
            vector<int> res;
            int maxDeep=0;
            rightSideViewCore(root,res,1,maxDeep);
            return res;
        }
    };
  • 相关阅读:
    python-day49--前端 css-层叠样式表
    python-day49--前端 html
    python-day48--mysql之视图、触发器、事务、存储过程、函数
    python-day47--pymysql模块
    python-day47--mysql数据备份与恢复
    python-day46--前端基础之html
    python-day45--mysql索引
    window系统下远程部署Tomcat
    tomcat下部署应用helloworld
    tomcat配置文件context.xml和server.xml分析
  • 原文地址:https://www.cnblogs.com/tianzeng/p/12462076.html
Copyright © 2011-2022 走看看