Youneed to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
这一题很简单,广度优先遍历就能解决,但是想要时间最短可不容易,这里假如使用queue来实现广度优先遍历的话,时间会变长,当时假如使用list链表来实现广度优先遍历的话,时间会缩短很多,以后在做只涉及到头尾的操作的时候,使用List 链表会很快,比如以后在广度优先遍历的时候使用List 链表会很快
class Solution {
public:
vector<int> largestValues(TreeNode*root) {
vector<int> result;
if (root == NULL) return result;
queue< TreeNode *> store;
TreeNode* p;
store.push(root);
int t = 1;
int u = 0;
int max=INT_MIN;
while (!store.empty())
{
p = store.front();
store.pop();
t--;
if (p->val > max) max =p->val;
if (p->left != NULL) { store.push(p->left);u++; }
if (p->right != NULL) {store.push(p->right); u++; }
if (t == 0)
{
result.push_back(max);
t = u;
max = INT_MIN;
u = 0;
}
}
return result;
}
};