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

Posted PJCK

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(二叉树 bfs) leetcode 199. 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.

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的主要内容,如果未能解决你的问题,请参考以下文章

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

leetcode 199 二叉树的右视图

[LeetCode] 199. 二叉树的右视图

leetcode 199 从右看二叉树

LeetCode Java刷题笔记—199. 二叉树的右视图

java 199.二叉树右侧视图(BFS).java