: https://leetcode.com/problems/find-largest-value-in-each-tree-row
: 515. Find Largest Value in Each Tree Row
: 给你一个二元树,找出每一个 level 最大的元素列表。
: Example 1:
: https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg
: Input: root = [1,3,2,5,3,null,9]
: Output: [1,3,9]
: Example 2:
: Input: root = [1,2,3]
: Output: [1,3]
思路:
跟R大一样用BFS遍历,这边补上C++和Python作法
========== Python Code
from collections import deque
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
if (root == None):
return []
queue = deque()
queue.append(root)
ret = []
while(queue):
qsize = len(queue)
maxval = -float('inf')
for i in range(qsize):
node = queue.popleft()
maxval = max(maxval, node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
ret.append(maxval)
return ret
========== C++ Code
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode*> q;
vector<int> ret;
if (root == nullptr) return ret;
q.push(root);
while(!q.empty())
{
int qsize = q.size();
int maxval = INT_MIN;
for (int i = 0; i < qsize; ++i)
{
TreeNode* node = q.front();
q.pop();
maxval = max(node->val, maxval);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
ret.push_back(maxval);
}
return ret;
}
};