题目来源 点击打开链接
题目详情 You need to find the largest value in each row of a binary tree.
题目思路 构建结构向量存放在每层得到的最大值,通过深度优先搜索在每层找到一个值,再进行迭代在每层找出一个值和向量中已有的值比较,直到结束得到最终结果。
代码段
class Solution {
private:
vector<int> ans;
void preorder(TreeNode* root, int height) {
if (!root) return;
if (ans.size() < height) ans.push_back(root->val);
else ans[height - 1] = max(ans[height - 1], root->val);
preorder(root->left, height + 1);
preorder(root->right, height + 1);
}
public:
vector<int> largestValues(TreeNode* root) {
preorder(root, 1);
return ans;
}
};
转载请注明原文地址: https://ju.6miu.com/read-32684.html