zoukankan      html  css  js  c++  java
  • 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);
        }
    };
    
  • 相关阅读:
    NOIP模拟测试17
    C++11下的关键字
    Tyvj 1518 CPU监控(线段树)
    单身三连之三
    论求解线性方程
    单身三连之二
    单身三连之一
    20190719总结
    卡常
    论突变为零(不定更新)
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7526049.html
Copyright © 2011-2022 走看看