515.在每个树行中找到最大值

在这里插入图片描述

思路:BFS广度优先搜索,用for循环依次搜索树的每一层。

这道题目很经典


/**
 * 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) {
  queue<TreeNode*> q;
  vector<int> v;
  if (!root) return v;
  TreeNode* p = root;
  q.push(p);
  while (!q.empty())
  {
   int size = q.size(), max = INT_MIN;
   for (int i = 0; i < size; ++i)
   {
    p = q.front();
    q.pop();
    if (p->val > max) max = p->val;
    if (p->left) q.push(p->left);
    if (p->right) q.push(p->right);
   }
   v.push_back(max);
  }
  return v;
 }
};

在这里插入图片描述

发布了90 篇原创文章 · 获赞 7 · 访问量 2174

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/103029395
今日推荐