515. Find Largest Value in Each Tree Row 找到数每一层的最大值

来源:互联网 发布:淘宝判定为广告的评价 编辑:程序博客网 时间:2024/05/28 05:14

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]这个题目较简单。使用一个队列保存一层树。弹出的过程统计最大值即可
/** * 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<int> res;        if(root==nullptr)            return res;        queue<TreeNode*> q;        q.push(root);        while(!q.empty())        {            int n=q.size();            int tempmax=numeric_limits<int>::min();            while(n--)            {                TreeNode* cur=q.front();                q.pop();                if(cur->left) q.push(cur->left);                if(cur->right) q.push(cur->right);                tempmax=max(tempmax,cur->val);            }            res.push_back(tempmax);        }        return res;    }};


原创粉丝点击