二叉树的右视图(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;
    }
};
相关推荐
甄心爱学习6 分钟前
KMP算法(小白理解)
开发语言·python·算法
wen__xvn28 分钟前
牛客周赛 Round 127
算法
大锦终30 分钟前
dfs解决FloodFill 算法
c++·算法·深度优先
橘颂TA43 分钟前
【剑斩OFFER】算法的暴力美学——LeetCode 200 题:岛屿数量
算法·leetcode·职场和发展
苦藤新鸡1 小时前
14.合并区间(1,3)(2,5)=(1,5)
c++·算法·leetcode·动态规划
程序员-King.1 小时前
day145—递归—二叉树的右视图(LeetCode-199)
算法·leetcode·二叉树·递归
漫随流水1 小时前
leetcode算法(112.路径总和)
数据结构·算法·leetcode·二叉树
过期的秋刀鱼!1 小时前
机器学习-带正则化的成本函数-
人工智能·python·深度学习·算法·机器学习·逻辑回归
ScilogyHunter1 小时前
前馈/反馈控制是什么
算法·控制
山峰哥1 小时前
SQL调优实战:让查询效率飙升10倍的降本密码
服务器·前端·数据库·sql·编辑器·深度优先