LeetCode 515. Find Largest Value in Each Tree Row 20170626本周
2017-06-26 19:40 方小呆dai 阅读(132) 评论(0) 收藏 举报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]
题目大意:输出树的每一层的最大值
解题思路:广度优先遍历图,输出每一层的最大值

class Solution {
public:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode *> que;
vector<int> vec;
if (!root) return vec;
que.push(root);
while(!que.empty()) {
int size = que.size();
int max = INT_MIN;
while (size--) {
TreeNode *node = que.front();
que.pop();
if(node->val > max) max = node->val;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
vec.push_back(max);
}
return vec;
}
};
浙公网安备 33010602011771号