前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 199. Binary Tree Right Side View

LeetCode 199. Binary Tree Right Side View

作者头像
ShenduCC
发布2020-02-19 10:57:33
2910
发布2020-02-19 10:57:33
举报
文章被收录于专栏:算法修养

题目

题意:假如你在一棵二叉树的右边,往左看,能看到哪些元素。

题解:广搜,每一层的最右边元素即可。

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
struct Node
{
    TreeNode* node;
    int num;
    Node(){}
    Node(TreeNode* node,int num)
    {
        this->node = node;
        this->num = num;
    }
};
class Solution {
public:
    vector<int> ans;
    vector<int> rightSideView(TreeNode* root) {
        
        if(root==NULL)
            return ans;
        queue<Node> q;
        q.push(Node(root,0));
        
        int num = 0;
        while(!q.empty())
        {
            Node term = q.front();
            q.pop();
            
            if(q.empty()||q.front().num != term.num)
            {
                ans.push_back(term.node->val);
            }
            
            if(term.node->left!=NULL)
                q.push(Node(term.node->left,term.num+1));
            if(term.node->right!=NULL)
                q.push(Node(term.node->right,term.num+1));
        }
        
        return ans;
        
        
    }
    
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-02-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档