515 Find Largest Value in Each Tree Row 在每个树行中找最大值

Posted lina2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了515 Find Largest Value in Each Tree Row 在每个树行中找最大值相关的知识,希望对你有一定的参考价值。

在二叉树的每一行中找到最大的值。
示例:
输入:
          1
         /  \
        3   2
       /  \    \  
      5   3    9
输出: [1, 3, 9]

详见:https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/

C++:

/**
 * 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) {
        if(!root)
        {
            return {};
        }
        vector<int> res;
        queue<TreeNode*> que;
        que.push(root);
        int cur=1;
        int mx=INT_MIN;
        while(!que.empty())
        {
            root=que.front();
            que.pop();
            --cur;
            if(root->val>mx)
            {
                mx=root->val;
            }
            if(root->left)
            {
                que.push(root->left);
            }
            if(root->right)
            {
                que.push(root->right);
            }
            if(cur==0)
            {
                cur=que.size();
                res.push_back(mx);
                mx=INT_MIN;
            }
        }
        return res;
    }
};

 

以上是关于515 Find Largest Value in Each Tree Row 在每个树行中找最大值的主要内容,如果未能解决你的问题,请参考以下文章

515. Find Largest Value in Each Tree Row

515. Find Largest Value in Each Tree Row

[LeetCode]515 Find Largest Value in Each Tree Row(dfs)

leetcode--515. Find Largest Value in Each Tree Row

[leetcode-515-Find Largest Value in Each Tree Row]

(BFS 二叉树) leetcode 515. Find Largest Value in Each Tree Row