1、Find Largest Value in Each Tree Row
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]
这个题第一反应应该就是广度优先,毕竟要每层都遍历完找个最大值嘛,用队列是没错的了,但是如何区分好每一层,取最大存入vector是个问题,开始打算用pair,存level,但是遇到种种问题,可能也能行得通但是有些麻烦。不如用空指针作为间隔,每一层入队结束后,放入一个空指针,当遇到空指针时,说明这一层的数都比较完了,把max放入vector,同时也代表下一层刚好入队结束,又可以放一个空指针,结束此次循环进入下一个节点就好了。最后一层的最大值,由于遇到最后一个空指针时,size刚好为1就跳出了,所以循环结束把最后一个max放入。
求最大值时,max常设为INT_MIN,反之求最小min就设为INT_MAX.
/**
* 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:
vector<int> largestValues(TreeNode* root) {
vector<int> result;
if(!root) return result;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
int max=INT_MIN;
while(q.size()!=1){
TreeNode* temp=q.front();
q.pop();
if(!temp){
result.push_back(max);
q.push(NULL);
max=INT_MIN;
continue;
}
else if(temp->val>max)
max=temp->val;
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
result.push_back(max);
return result;
}
};