515. Find Largest Value in Each Tree Row | Breadth-first Search

来源:互联网 发布:php 中class exists 编辑:程序博客网 时间:2024/06/08 05:35

Description

You need to find the largest value in each row of a binary tree.
Example:
这里写图片描述
Difficluty:Medium

Thinking

典型的广度优先搜索算法题。用BFS遍历树,再用一个数组记录每一行的最大值即可。for循环遍历一层的条件是 i < size,size是下层子节点push进队列前的queue.size();

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) {        if(!root) return {};        vector<int> maxv;        queue<TreeNode*> q;        q.push(root);         while(!q.empty()){            int max = INT_MIN;            int size = q.size();            for(int i = 0; i < size; i++){                TreeNode* temp = q.front();                q.pop();                if(max < temp->val) max = temp->val;                if(temp->left) q.push(temp->left);                if(temp->right) q.push(temp->right);            }           maxv.push_back(max);        }        return maxv;    }};
原创粉丝点击