Find Largest Value in Each Tree Row @LeetCode

PROBLEM :

You need to find the largest value in each row of a binary tree.

Example:
Input:

          1
         / \
        3   2
       / \   \
      5   3   9

Output: [1, 3, 9]

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/**
 * 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> largestValues(TreeNode* root) {
       
        vector<int> vec ;
        if(!root)
            return vec ;
           
        queue<TreeNode*> que ;
        que.push(root) ;
       
        while(!que.empty())
        {
            int size=que.size() ;
            int max=INT_MIN ;
            while(size--)
            {
                TreeNode* curr=que.front() ;
                que.pop() ;
               
                if(curr->val>max)
                    max=curr->val ;
                   
                if(curr->left)
                    que.push(curr->left) ;
                   
                if(curr->right)
                    que.push(curr->right) ;
            }
            vec.push_back(max) ;
        }
        return vec ;
    }
};

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )