LeetCode——Find Largest Value in Each Tree Row

Question

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]

Solution

层次遍历。

Code

/**
 * 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 == NULL)
            return vector<int>();
        queue<TreeNode*> rows, new_rows;
        new_rows.push(root);
        rows = new_rows;
        vector<int> res;
        int max_value = INT_MIN;
        while (!new_rows.empty()) {
            max_value = INT_MIN;
            clear(new_rows);
            while (!rows.empty()) {
                TreeNode* tmp = rows.front();
                if (tmp->val > max_value)
                    max_value = tmp->val;
                rows.pop();
                if (tmp->left != NULL)
                    new_rows.push(tmp->left);
                if (tmp->right != NULL)
                    new_rows.push(tmp->right);
            }
            res.push_back(max_value);
            rows = new_rows;
        }
        return res;
    }
    void clear(queue<TreeNode*>& q) {
        queue<TreeNode*> empty;
        swap(q, empty);
    }
};
posted @ 2017-09-15 13:49  清水汪汪  阅读(183)  评论(0编辑  收藏  举报