二叉树的右视图(BFS或DFS)

思路:

1.BFS,使用队列模拟BFS,层序遍历二叉树,从右子树开始遍历,每层第一个访问的就是最右边的那个结点。

2.DFS,使用栈模拟DFS,从右子树开始遍历,遍历到底。对树进行深度优先搜索,在搜索过程中,总是先访问右子树。那么对于每一层来说,我们在这层见到的第一个结点一定是最右边的结点。

3.都需要知道当前结点在哪一层,所以要用map记录。可以存储在每个深度访问的第一个结点,一旦我们知道了树的层数,就可以得到最终的结果数组。

cpp 复制代码
//BFS
/**
 * 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) {
        if(root==nullptr) return {};
        unordered_map<int,int> num;
        queue<pair<TreeNode*,int>> node_depth;
        node_depth.push({root,0});
        int maxdep=-1;
        while(!node_depth.empty()){
            auto p=node_depth.front(); node_depth.pop();
            TreeNode* nod=p.first;
            int dep=p.second;
            

            if(nod!=nullptr){
                maxdep=max(maxdep,dep);
                if(num.find(dep) == num.end()){
                    num[dep]=nod->val;
                }
                node_depth.push({nod->right,dep+1});
                node_depth.push({nod->left,dep+1});

            } 
        }
        vector<int> rightsort;
        for(int i=0;i<=maxdep;i++){
            rightsort.push_back(num[i]);
        }

        return rightsort;
    }
};

//DFS
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if(root==nullptr) return {};
        unordered_map<int,int> num;
        stack<pair<TreeNode*,int>> node_depth;
        node_depth.push({root,0});
        int maxdep=-1;
        while(!node_depth.empty()){
            auto p=node_depth.top(); node_depth.pop();
            TreeNode* nod=p.first;
            int dep=p.second;
            

            if(nod!=nullptr){
                maxdep=max(maxdep,dep);
                if(num.find(dep) == num.end()){
                    num[dep]=nod->val;
                }
                node_depth.push({nod->left,dep+1});
                node_depth.push({nod->right,dep+1});

            } 
        }
        vector<int> rightsort;
        for(int i=0;i<=maxdep;i++){
            rightsort.push_back(num[i]);
        }

        return rightsort;
    }
};
相关推荐
1104.北光c°1 小时前
滑动窗口HotKey探测机制:让你的缓存TTL更智能
java·开发语言·笔记·程序人生·算法·滑动窗口·hotkey
仰泳的熊猫5 小时前
题目2570:蓝桥杯2020年第十一届省赛真题-成绩分析
数据结构·c++·算法·蓝桥杯
无极低码8 小时前
ecGlypher新手安装分步指南(标准化流程)
人工智能·算法·自然语言处理·大模型·rag
软件算法开发8 小时前
基于海象优化算法的LSTM网络模型(WOA-LSTM)的一维时间序列预测matlab仿真
算法·matlab·lstm·一维时间序列预测·woa-lstm·海象优化
superior tigre9 小时前
22 括号生成
算法·深度优先
努力也学不会java10 小时前
【缓存算法】一篇文章带你彻底搞懂面试高频题LRU/LFU
java·数据结构·人工智能·算法·缓存·面试
旖-旎10 小时前
二分查找(x的平方根)(4)
c++·算法·二分查找·力扣·双指针
ECT-OS-JiuHuaShan11 小时前
朱梁万有递归元定理,重构《易经》
算法·重构
智者知已应修善业11 小时前
【51单片机独立按键控制数码管移动反向,2片74CH573/74CH273段和位,按键按下保持原状态】2023-3-25
经验分享·笔记·单片机·嵌入式硬件·算法·51单片机