https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/
Solution 1. Recursion.
void levelOrder(TreeNode* node, vector<int>& res, int lev) {
if(!node) return;
if(res.size() == lev) res.push_back(node->val);
else
res[lev] = res[lev] > node->val ? res[lev] : node->val;
levelOrder(node->left, res, lev+1);
levelOrder(node->right, res, lev+1);
}
vector<int> largestValues(TreeNode* root) {
vector<int> res;
levelOrder(root, res, 0);
return res;
}
Solution 2.
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
int mx = INT_MIN;
while(!q.empty()) {
TreeNode* node = q.front();
q.pop();
if(node == nullptr) {
res.push_back(mx);
mx = INT_MIN;
if(!q.empty())
q.push(nullptr);
}
else {
mx = mx>node->val ? mx : node->val;
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
}
return res;
}
No comments:
Post a Comment