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]
Subscribe to see which companies asked this question.
AC:
/**
* 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 {
vector<int> res;
public:
vector<int> largestValues(TreeNode* root) {
if(root==NULL)
return res;
findlarge(root,0);
return res;
}
void findlarge(TreeNode* root,int level)
{
if(root==NULL)
return;
if(res.size()<level+1)
res.push_back(root->val);
else {
if (res[level] < root->val) {
res[level] = root->val;
}
}
findlarge(root->left, level+1);
findlarge(root->right, level+1);
}
};