二叉树的右视图(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;
    }
};
相关推荐
vortex5几秒前
几种 dump hash 方式对比分析
算法·哈希算法
Wei&Yan1 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
团子的二进制世界2 小时前
G1垃圾收集器是如何工作的?
java·jvm·算法
吃杠碰小鸡2 小时前
高中数学-数列-导数证明
前端·数学·算法
故事不长丨2 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
long3162 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
近津薪荼2 小时前
dfs专题4——二叉树的深搜(验证二叉搜索树)
c++·学习·算法·深度优先
熊文豪2 小时前
探索CANN ops-nn:高性能哈希算子技术解读
算法·哈希算法·cann
熊猫_豆豆2 小时前
YOLOP车道检测
人工智能·python·算法
艾莉丝努力练剑2 小时前
【Linux:文件】Ext系列文件系统(初阶)
大数据·linux·运维·服务器·c++·人工智能·算法