问题描述:
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]
解法思路:
跟第十周的算法思路类似,在层次遍历时记下每个节点——当到达新一层时,将当前节点的值放入vector中;在之后的同层遍历中,如果有比它大的就替换。
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> result;
if(root != NULL) {
queue<int>level;
queue<TreeNode*>node;
node.push(root);
level.push(1);
result.push_back(root->val);
int m = 1;
while(!node.empty()) {
TreeNode* cur_n = node.front();
int cur_l = level.front();
if(cur_n->left) {
node.push(cur_n->left);
level.push(cur_l+1);
}
if(cur_n->right) {
node.push(cur_n->right);
level.push(cur_l+1);
}
node.pop();
level.pop();
if(m == cur_l) {
if(cur_n->val > result[m-1])
result[m-1] = cur_n->val;
}
else {
m++;
result.push_back(cur_n->val);
}
}
}
return result;
}
};
算法的执行时间复杂度为
O(n)
。
休息下,这波不亏~