Binary Tree Right Side View | February Leetcoding Challenge 2021| Day 6
logo
Manas Sinha
Developer | Designer

By Manas | 6 February 2021

February LeetCoding Challenge 2021

Day6

Binary Tree Right Side View

PROBLEM  STATEMENT: 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.
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

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

Explanation

This problem can be easily solved by using BFS.  Hypothetically, if you could see the tree from the right-side, at every level only the rightmost node is visible. That is basically the solution 🙂
ALGORITHM:
  • Traverse the tree in breadth first order
  • At every level add the right most node the list.

code

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if(!root) return {};
        queue<TreeNode*> q;
        q.push(root);
        
        vector<int> right_view;
        int right_most_node;
        while(!q.empty()){
            int n = q.size();
            
            for(int i=0;i<n;++i){  
                TreeNode* front = q.front();
                q.pop();
                if(front->left) q.push(front->left);
              	if(front->right) q.push(front->right);
              	if(i == n-1) right_view.push_back(front->val);
            }
        }
        return right_view;
    }
};

LEAVE A COMMENT

If you like the post leave a comment and share it.

This Post Has One Comment

  1. Anonymous

    Post All the remaining

Leave a Reply