week15
题目
You need to find the largest value in each row of a binary tree.
原题地址:https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/
解析
题目要求给定一棵二叉树,找出每一层的最大的节点的值。
大致思路是先对树进行一次遍历,用一个新的二维数组记录每个节点的值及所在的层数,最后对层数相同的节点进行比较找出最大值。
代码
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> null;
if (root == NULL) {
return null;
}
vector<pair<int, int>> data;
int depth = 0;
int maxDepth = -1;
recursive(root, data, depth, maxDepth);
vector<int> result(maxDepth + 1);
bool* flag = new bool[maxDepth + 1];
for (int i = 0; i < maxDepth + 1; ++i) {
result[i] = 0;
flag[i] = false;
}
for (int i = 0; i < data.size(); ++i) {
if (!flag[data[i].first]) {
result[data[i].first] = data[i].second;
flag[data[i].first] = true;
}
else if (data[i].second > result[data[i].first]) {
result[data[i].first] = data[i].second;
}
}
return result;
}
/*对二叉树按深度优先遍历,找出每个节点的值及对应所在的层数,记录在data中*/
void recursive(TreeNode* root, vector<pair<int, int>>& data, int& depth, int& maxDepth) {
/*maxDepth用来记录树的最大高度*/
maxDepth = depth > maxDepth ? depth : maxDepth;
pair<int, int> tmp;
tmp.first = depth;
tmp.second = root->val;
data.push_back(tmp);
if (root->left != NULL) {
++depth;
recursive(root->left, data, depth, maxDepth);
--depth;
}
if (root->right != NULL) {
++depth;
recursive(root->right, data, depth, maxDepth);
--depth;
}
}
};