二叉树的右视图(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;
    }
};
相关推荐
2301_764441331 天前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI1 天前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly1 天前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives1 天前
atcoder ABC 452 题解
数据结构·算法
feifeigo1231 天前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
fengfuyao9851 天前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神1 天前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜1 天前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
Proxy_ZZ01 天前
用Matlab绘制BER曲线对比SPA与Min-Sum性能
人工智能·算法·机器学习
黎阳之光1 天前
黎阳之光:以视频孪生领跑全球,赋能数字孪生水利智能监测新征程
大数据·人工智能·算法·安全·数字孪生