二叉树的右视图(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;
    }
};
相关推荐
zheyutao1 小时前
字符串哈希
算法
A尘埃1 小时前
保险公司车险理赔欺诈检测(随机森林)
算法·随机森林·机器学习
大江东去浪淘尽千古风流人物2 小时前
【VLN】VLN(Vision-and-Language Navigation视觉语言导航)算法本质,范式难点及解决方向(1)
人工智能·python·算法
努力学算法的蒟蒻2 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495642 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
AC赳赳老秦3 小时前
2026国产算力新周期:DeepSeek实战适配英伟达H200,引领大模型训练效率跃升
大数据·前端·人工智能·算法·tidb·memcache·deepseek
2401_841495643 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
budingxiaomoli3 小时前
优选算法-字符串
算法
qq7422349843 小时前
APS系统与OR-Tools完全指南:智能排产与优化算法实战解析
人工智能·算法·工业·aps·排程
A尘埃4 小时前
超市购物篮关联分析与货架优化(Apriori算法)
算法