在每个树行中找最大值
题目描述:
前序遍历(Preorder Traversal 亦称先序遍历)——访问根结点的操作发生在遍历其左右子树之前。
需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9输出: [1, 3, 9]
来源:力扣(LeetCode)
OJ链接分析:
这道题是层序遍历的扩折, 是在层序层序遍历的基础上在找每一层的最大值, 上代码
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<TreeNode*> tq1, tq2;
vector<int> max;
TreeNode* cur;
if (root) tq1.push_back(root);
int tmpmax;
while (!tq1.empty() || !tq2.empty()) {
for (tmpmax = tq1.front()->val;tq1.size() > 0;) {
cur = tq1.back();
if (cur->val > tmpmax)tmpmax = cur->val;
if (cur->left)tq2.push_back(cur->left);
if (cur->right)tq2.push_back(cur->right);
tq1.pop_back();
}
max.push_back(tmpmax);
tq1 = tq2;
tq2.clear();
}
return max;
}
};
层序遍历储存上一层节点指针的数据结构还可以是其他, 但vector比较快一点, 比如还可以用双端队列deque
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
deque<TreeNode*> tq;
vector<int> max;
TreeNode* cur;
if (root) tq.push_back(root);
int size, tmpmax;
while (!tq.empty()) {
size = tq.size();
for (tmpmax =tq.front()->val; size > 0; --size) {
cur = tq.front();
if (cur->val > tmpmax)tmpmax = cur->val;
if (cur->left)tq.push_back(cur->left);
if (cur->right)tq.push_back(cur->right);
tq.pop_front();
}
max.push_back(tmpmax);
}
return max;
}
};