C++Leetcod515:在每个树行中找最大值

题目
您需要在二叉树的每一行中找到最大的值。

示例:
输入:

      1
     / \
    3   2
   / \   \  
  5   3   9 

输出: [1, 3, 9]

思路
1、BFS。连续这几道题,思路都是一样的,只是根据要求输出的结果不同,做一些相应的改动,主干部分都类似。
2、简化写法。

实现方法
一、BFS

/**
 * 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) return res;
        
        queue<TreeNode*> q,tmp;
        q.push(root);
        while(!q.empty()){
            int count=q.size();
            //遍历一层,找到最大值
            tmp=q;
            int vmax=q.front()->val;
            for(int i=0;i<count;i++){
                vmax=max(vmax,tmp.front()->val);
                tmp.pop();
            }
            res.push_back(vmax);
            //将下一层的元素放入队列中
            while(count>0){
                TreeNode* top=q.front();
                q.pop();
                count--;
                if(top->left) q.push(top->left);
                if(top->right) q.push(top->right);
            }  
        }
        return res;
    }
};

二、简化写法

/**
 * 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) return res;
        
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int count=q.size();
            int vmax=q.front()->val;
            while(count--){
                TreeNode* top=q.front();
                q.pop();
                if(top->val>vmax) vmax=top->val;	//遍历时,直接判断大小,将最大的值保存下来
                if(top->left) q.push(top->left);
                if(top->right) q.push(top->right);
            } 
            res.push_back(vmax);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值