leetcode 515. tree to find the maximum value in each row

Subject description:

You need to find the maximum value in each row of the binary tree.

Example:

输入: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

输出: [1, 3, 9]

solution:

/**
 * 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<TreeNode*> cur(1, root);
        vector<TreeNode*> nxt;
        if(root == NULL){
            return {};
        }else{
            vector<int> res;
            while(!cur.empty()){
                nxt.clear();
                int val = INT_MIN;
                for(TreeNode* node : cur){
                    val = max(val, node->val);
                    if(node->left){
                        nxt.push_back(node->left);
                    }
                    if(node->right){
                        nxt.push_back(node->right);
                    }
                }
                res.push_back(val);
                cur = nxt;
            }
            return res;
        }
    }
};

Guess you like

Origin www.cnblogs.com/zhanzq/p/11081607.html