码迷,mamicode.com
首页 > 其他好文 > 详细

(二叉树 bfs) leetcode 199. Binary Tree Right Side View

时间:2019-04-17 09:28:30      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:size   value   red   def   public   bsp   code   ati   ima   

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.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   2     3         <---
 \       5     4       <---
--------------------------------------------------------------------------------------------------
水。。。。。。用bfs就可以快速先解决掉了

C++代码:
/**
 * 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> vec;
        if(!root) return vec;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            for(int i = q.size(); i > 0; i--){
                auto t = q.front();
                q.pop();
                if(i == 1){
                    vec.push_back(t->val);
                }
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
        }
        return vec;
    }
};

 

(二叉树 bfs) leetcode 199. Binary Tree Right Side View

标签:size   value   red   def   public   bsp   code   ati   ima   

原文地址:https://www.cnblogs.com/Weixu-Liu/p/10721265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!