您的位置:首页 > 产品设计 > UI/UE

515[Medium]:Find Largest Value in Each Tree Row

2017-11-03 09:07 459 查看
Part1:题目描述

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]

Part2:解题思路
这道题目放在深搜到下面,我本来打算用深搜,想了一下,他要求每层的最大值,明显是一层一层的搜索<=>广搜,最后还是决定用广搜了。我觉得这次的代码,我个人觉得还是比较满意的:用一个vector存我们要的结果,queue用来存当前的这一层的节点,通过一个for循环来找出当前这一层的最大值,且每比较完一个节点我们就把他的左右孩子放到queue里,把它本身从队列里踢出去。
遇到的一个问题,就是只有用下面这一句向vector里面放值才能成功,注释掉的2句都不可以,现在也还没想明白为啥,欢迎大家来帮我解决这个疑惑!result.push_back(max);

Part3:代码

vector<int> largestValues(TreeNode* root) {
vector<int> result;
if (root == NULL) return result;
queue<TreeNode*> node;
node.push(root);
int index = 0;
while(!node.empty()) {
int levelSize = node.size();
int max = INT_MIN;
for(int i = 0; i < levelSize; i++) {
// 找每层的最大值
if (node.front()->val > max) {
max = node.front()->val;
}
// 将下一层的节点放到queue中
if (node.front()->left != NULL) {
node.push(node.front()->left);
}
if (node.front()->right != NULL) {
node.push(node.front()->right);
}
// 清除当前层中的节点
node.pop();
}
result.push_back(max);
//result.at(index++) = max;
//result[index++] = max;
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ BFS