当前位置: 代码迷 >> 综合 >> LeetCode第515题解析
  详细解决方案

LeetCode第515题解析

热度:95   发布时间:2024-02-05 04:55:49.0

 

您需要在二叉树的每一行中找到最大的值。

示例:

输入: 1/ \3   2/ \   \  5   3   9 输出: [1, 3, 9]
class Solution {
public://DFSvector<int> largestValues(TreeNode* root) {vector<int> res;queue<TreeNode*> que;if(root) que.push(root);while(!que.empty()) {int length = que.size();int maxValue = INT_MIN;for(int i = 0; i < length; ++i) {TreeNode* tmp = que.front();que.pop();maxValue = max(maxValue, tmp->val);if(tmp->left) que.push(tmp->left);if(tmp->right) que.push(tmp->right);}res.push_back(maxValue);}return res;}
};
class Solution {
public:vector<int> largestValues(TreeNode* root) {vector<int> res;bfs(0, root, res);return res;}void bfs(int level, TreeNode* root, vector<int>& res) {if(root) {if(level >= res.size()) res.push_back(root->val);else res[level] = max(res[level], root->val);res[level] = max(res[level], root->val);bfs(level + 1, root->left, res);bfs(level + 1, root->right, res);}}
};