leetcode:199. 二叉树的右视图

题目来源

题目描述

在这里插入图片描述

class Solution {
public:
    vector<int> rightSideView(TreeNode* root){
 
    }
};

题目解析

使用层序遍历,并只保留每层最后一个节点的值

层序遍历

vector<int> rightSideView(TreeNode* root) {
    vector<int> ans;
    if(root == NULL){
        return ans;
    }
    std::queue<TreeNode *> queue;
    queue.push(root);
    while (!queue.empty()){
        int size = queue.size();
        for (int i = 0; i < size; ++i) {
            TreeNode *peek = queue.front();
            queue.pop();
            if(i == size -1){
                ans.push_back(peek->val);
            }
            if(peek->left){
                queue.push(peek->left);
            }
            if(peek->right){
                queue.push(peek->right);
            }
        }
    }
    
    return ans;
}

递归

我们对树进行深度优先搜索,在搜索过程中,我们总是先访问右子树。那么对于每一层来说,我们在这层见到的第一个结点一定是最右边的结点。

在这里插入图片描述

// 树中的节点数在 [1, 104]范围内
void  helper(TreeNode* root, int depth, vector<int> &ans){
    if(root == NULL){
        return;
    }
    
    if(ans.size() == depth){
        ans.push_back(root->val);
    }
    
    helper(root->right, depth + 1, ans);
    helper(root->left, depth + 1, ans);
}

vector<int> rightSideView(TreeNode* root) {
    vector<int> ans;
    helper(root, 0, ans);
    return ans;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值