题目:
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]
找到二叉树每行最大的数。
分析:
第一眼看过去,题目要求一行一行找最大,自然想到 [bfs]:
不过课本上的bfs使用了queue来装节点,虽然一层一层地插入了,可是好像不能很明显地分出层次。如果解决了这个问题,接下来只要对每一层进行排序,选取最大数就好(可以用stl里的sort)。我的解决方法是,在遍历新的一层时,先把节点读到一个容器里,然后再转移到用来递归的容器。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//bfs 递归,father是装遍历节点的容器,就是课本(博客上文图片)上的q,res装每一层的值
void addQueue(vector<vector<int> >&res, vector<TreeNode*>&father) {
//(1)
//father不空,还有节点未遍历
if (!father.empty()) {
vector<TreeNode*> son; //装每一层的节点,然后转移给father
vector<int> son2; //装节点的值,转移到res
while (!father.empty()) {
TreeNode* fir = father.front();
if (fir->left != NULL)
son.push_back(fir->left);
if (fir->right != NULL)
son.push_back(fir->right);
father.erase(father.begin());
}
vector<TreeNode*>::iterator it = son.begin(); //把节点值取出给son2
while (it != son.end()) {
TreeNode* fir = *it;
son2.push_back(fir->val);
++it;
}
//(2)
if(!son2.empty())
res.push_back(son2);
//son的节点转移到father,进行一次新的遍历
while (!son.empty()) {
father.push_back(son.front());
son.erase(son.begin());
}
addQueue(res, father);
}
}
//为sort逆序排序提供的函数
static bool com(int a, int b) {
return a > b;
}
//
vector<int> largestValues(TreeNode* root) {
vector<vector<int> >res;
vector<TreeNode*> father;
vector<int> son2;
if (root != NULL) {
father.push_back(root);
son2.push_back(root->val);
res.push_back(son2);
}
addQueue(res, father);
vector<int> hhh;
for (int i = 0; i < res.size(); i++) {
sort(res[i].begin(), res[i].end(),com); //(3)
hhh.push_back(res[i].front());
}
return hhh;
}
};
(1):bfs里用vector代替了queue,这是为了后面操作方便决定的,因为sort要输入容器迭代器来排序,但是queue没有
(2):
if(!son2.empty())
(3)sort可以传递函数指针(代码中的com),关于函数指针和函数对象的具体用法参见:点击打开链接