您的位置:首页 > 其它

第三周作业

2017-03-12 12:34 197 查看
题目来源  点击打开链接

题目详情   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;
}
};



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: