1. 程式人生 > >515 Find Largest Value in Each Tree Row 在每個樹行中找最大值

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

left urn 找最大值 empty script com init min right

在二叉樹的每一行中找到最大的值。
示例:
輸入:
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 在每個樹行中找最大值