LeetCode 199-Right View of Binary Tree (BFS)

1. Topic introduction

Given a binary tree, imagine yourself standing on the right side of it, and return the node values ​​that can be seen from the right side in order from top to bottom.

Example:

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

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

Source: LeetCode
Link: https://leetcode-cn.com/problems/binary-tree-right-side-view The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

  • Traverse the binary tree by layer, and save the rightmost node value of each layer to the output array, which is the right view of the binary tree.

Three, problem-solving code

/**
 * 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*> que;
        que.push(root);
        while(!que.empty())
        {
            int len = que.size();
            for(int i = 0; i < len; ++i)
            {
                TreeNode* node = que.front();
                que.pop();
                if(i == len-1)
                    vec.push_back(node->val);
                if(node->left)
                    que.push(node->left);
                if(node->right)
                    que.push(node->right);
            }
        }
        return vec;
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/105690570