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;
    }
};

 

posted on 2018-04-22 16:36  lina2014  阅读(159)  评论(0编辑  收藏  举报

导航