二叉树的右视图-二叉树

199. 二叉树的右视图 - 力扣(LeetCode)

层序遍历,广度优先

queue先进后出,每层从左往右进树,最后一个就是最右边的数;pop掉这层的。push下一层;

cpp 复制代码
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if(root==nullptr)
            return vector<int>();

        vector<int>  rtnum;
        queue<TreeNode*> nodetree;

        nodetree.push(root);
        while(!nodetree.empty())
        {
            int size = nodetree.size();
            TreeNode* tmp;

            for(int i = 0; i < size; i++)
            {
                tmp = nodetree.front();
                nodetree.pop();
                if(tmp->left)
                    nodetree.push(tmp->left);
                if(tmp->right){nodetree.push(tmp->right);}
            }
            rtnum.push_back(tmp->val);
        }
        return rtnum;

    }
};

递归

遍历顺序改为根、右子树、左子树;

这样往下遍历,到达新一层的第一个节点就是右子树;

就是到达新的深度的第一个就是最右边的;

cpp 复制代码
class Solution {
    vector<int> ans;

    void dfs(TreeNode* node, int depth) {
        if (node == nullptr) {
            return;
        }
        if (depth == ans.size()) { // 这个深度首次遇到
            ans.push_back(node->val);
        }
        dfs(node->right, depth + 1); // 先递归右子树,保证首次遇到的一定是最右边的节点
        dfs(node->left, depth + 1);
    }

public:
    vector<int> rightSideView(TreeNode* root) {
        dfs(root, 0);
        return ans;
    }
};
相关推荐
小白菜又菜2 小时前
Leetcode 646. Maximum Length of Pair Chain
算法·leetcode·职场和发展
ヾ慈城3 小时前
【数据结构 - 二叉树】
c语言·数据结构·算法·链表
卡戎-caryon3 小时前
【项目实践】贪吃蛇
c语言·数据结构·算法
PeterClerk3 小时前
PCA算法降维代码示例
人工智能·算法·机器学习·pca
冲鸭嘟嘟可3 小时前
【数据结构】使用C语言 从零实现一个栈的数据结构
c语言·数据结构·算法
小白菜又菜4 小时前
Leetcode 516. Longest Palindromic Subsequence
算法·leetcode·职场和发展
℡☞小白☜ღ4 小时前
信号量(semaphore)
算法
IT_Beijing_BIT5 小时前
C++ 的常见算法 之一
开发语言·c++·算法
日月星辰cmc5 小时前
【算法题解】部分洛谷题解(下)
算法