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 ;
}
};
--------------------------------------------------------------------------------
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
Post a Comment