Leetcode: 515.Find Largest Value in Each Tree Row(Week10, Medium)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linwh8/article/details/78490955

注:本题采用的是BFS算法


Leetcode 515
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]

  • 题意:找到二叉树每一层的最大值,将之存储在vector数组中返回
  • 思路:使用BFS算法遍历每一层,分别求出每层的最大层
  • 算法:需要定义一个count用于区分每一层。故使用count等于队列的size
    • 当count != 0时,将左右节点加入队列中,且将该节点的值与当前最大值相比
    • 当count == 0时,将队列长度赋值给count,将当前最大值初始化为队列首部节点的值
    • 直至队列为空时,BFS遍历完成
  • 代码
/*
2017/11/9 515. Find largest Value in Each Tree Row
思路:采用BFS遍历每一层,用count来表示每一层。即将队列长度赋值给count,
      然后每执行一次循环,则count--,直至count = 0时,则完成一层的遍历
 */

/**
 * 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) {
        vector<int> result;
        if (root == NULL) return result;
        queue<TreeNode*> q;
        q.push(root);
        int count = q.size();
        int max = (q.front())->val;
        while(!q.empty()) {
            TreeNode* temp = q.front();
            q.pop();
            if (temp->val > max) max = temp->val;
            if (temp->left != NULL) q.push(temp->left);
            if (temp->right != NULL) q.push(temp->right);
            count--;
            if (count == 0) {
                result.push_back(max);
                count = q.size();
                if (count != 0) max = (q.front())->val;
            }
        }
        return result;
    }
};

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


猜你喜欢

转载自blog.csdn.net/linwh8/article/details/78490955