No199. Binary Tree Right Side View

一、题目描述

Given a binary tree, imagine yourself standing on theright side of it, return the values of the nodes you can see ordered from top to bottom.

For example:

Given the following binary tree,

   1            <---

 /   \

2     3         <---

 \     \

  5     4       <---


You should return [1, 3, 4].

二、解题思路

这道题与我之前写的No.515题目相类似,通过声明一个count的变量,用来计算每一层的节点的数量,在新的一层开始处理之前将count的值赋给n,然后count置为0,就可以继续计算新的一层的数量。对于每一层,只需要遍历n个元素即可,也就是变量i从0遍历到n-1,所以当i=n-1时,即为最右元素,写入答案数组即可。

三、代码实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        queue<TreeNode*> que;
        if(root==NULL) return res;
        que.push(root);
        int count=1;
        while(!que.empty()){
            int n = count;
            count = 0;
            for(int i=0;i<n;i++){
                TreeNode *q=que.front();
                que.pop();
                if(q->left!=NULL){
                    count++;
                    que.push(q->left);
                }
                if(q->right!=NULL){
                    count++;
                    que.push(q->right);
                }
                if(i==n-1) res.push_back(q->val);
            }
        }
        return res;
    }
};

四、其他解法

突然发现这道是分类到DFS中,而我用的是BFS,然后查看discuss发现这个DFS方法,还有点小精妙,该方法从根节点开始,先遍历右子节点,然后遍历左子节点,其判断条件(res.size()<level)表示第i层level中还没有最右元素存入res数组中,也就是res[i-1]表示level[i]中的最右元素。当第ilevel中的最右元素插入res中后,res.size()就等于level,如果res.size()<level,则向res中插入当前指针的val值。其中还有一点小精妙,level的值是按值传递,每一层有与其对应的独特值,而res是按引用调用,所以当res中插入最右元素后,其同层的左元素都不会满足条件,而插入数组了。

class Solution {
public:
    void recursion(TreeNode *root, int level, vector<int> &res)
    {
        if(root==NULL) return ;
        if(res.size()<level) res.push_back(root->val);
        recursion(root->right, level+1, res);
        recursion(root->left, level+1, res);
    }
    
    vector<int> rightSideView(TreeNode *root) {
        vector<int> res;
        recursion(root, 1, res);
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值