leetcode【BFS】-----515. Find Largest Value in Each Tree Row(在每一个树行中找最大值)

一、题目描述

二、分析

        这道题其实很简单,就是BFS,层序遍历,而后在这一层中找到最大的值保存下来,而后存入结果。node

三、代码

/**
 * 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==NULL) return res; 
        queue<TreeNode*> q;
        q.push(root);
        int size=0;
        int value;
        TreeNode* temp;
        while(!q.empty()){
            value=INT_MIN;
            size=q.size();
            for(int i=0;i<size;++i){
                temp=q.front();
                q.pop();
                value=max(temp->val,value);
                if(temp->left!=NULL){
                    q.push(temp->left);
                }
                if(temp->right!=NULL){
                    q.push(temp->right);
                }
            }
            res.push_back(value);
        }
        return res;
    }
};

四、相关知识点code

        树的层序遍历,BFS。blog

相关文章
相关标签/搜索