199. Binary Tree Right Side View

https://leetcode.com/problems/binary-tree-right-side-view/

Problem

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       <---

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> values;
        if (root == nullptr) return values;
        vector<TreeNode*> current{root};
        vector<TreeNode*> next;
        while (!current.empty()){
            values.emplace_back(current.front()->val);
            for (const auto &node: current) {
                if (node->right != nullptr) next.emplace_back(node->right);
                if (node->left != nullptr) next.emplace_back(node->left);    
            }
            current.swap(next);
            next.clear();
        }
        return values;
    }
};
  • #levelorder

  • #tree

Last updated

Was this helpful?