Binary Tree Right Side View - Medium - NL

less than 1 minute read

Published:

Question

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

Given the root of 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.

Approach

  • bfs with queue and height.

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> ans;
        if (root == NULL) {
            return ans;
        }
        
        queue<pair<TreeNode*, int> > q;
        q.push(make_pair(root, 0));
        int h = -1;
        
        while(!q.empty()) {
            TreeNode* t = q.front().first;
            int h1 = q.front().second;
            q.pop();
            if (h1 > h) {
                ans.push_back(t->val);
                h = h1;
            }
            if(t->right!=NULL) {
                q.push(make_pair(t->right, h1+1));
            }
            if(t->left!=NULL) {
                q.push(make_pair(t->left, h1+1));
            }
        }
        return ans;
    }
};