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;
        }
    };
  • 相关阅读:
    面试问烂的 MySQL 四种隔离级别,看完吊打面试官!
    注解Annotation实现原理与自定义注解例子
    趣图:苦逼的后端工程师
    session深入探讨
    趣图:听说996工作可以获得巨大成长
    面试官:一个 TCP 连接可以发多少个 HTTP 请求?
    聊聊前后端分离接口规范
    趣图:什么?需求文档又改了
    ASP.NET页面中去除VIEWSTATE视
    C#
  • 原文地址:https://www.cnblogs.com/tianzeng/p/12462076.html
Copyright © 2011-2022 走看看