Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right 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]

思路:题目要求是求一个二叉树的右视图。给出的tags上面有两种方式,DFS,和BFS。

方法一:DFS

(1)右视图看过来一个树,每一层如果这个层次上有节点存在的话,只有一个节点是会被添加到最后的结果res中的。

(2)这样,res的大小实际行就代表了当前访问的层次。

(3)考虑修改先序遍历的算法,当节点不为NULL的时候,如果访问的层次大于等于res的大小,说明访问到了接下来的一层,否则则说明在这个层次上已经有右边看过来的数据添加进来,当前的元素是会被右视图遮挡的。然后优先遍历右边,而后左边,注意不同于先序遍历

代码如下:

/**
 * 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;
        helper(root,0,res);
        return res;
    }
    
    void helper(TreeNode*root,int level,vector<int>&res)
    {
        if(!root)  
            return;
        if(level>=res.size())
            res.push_back(root->val);
        helper(root->right,level+1,res);
        helper(root->left,level+1,res);
    }
};
方法二:BFS

使用层次遍历的方式,每一层的最后一个元素添加到结果的数组res中返回就可以

代码如下所示:

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

    }
    return res;
    }
};



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值