515. Find Largest Value in Each Tree Row

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]

BFS+维护一个每行的长度+维护一个每行的max变量,每行遍历完之后把max压到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) {
        
        if(!root) return {};
        
        queue<TreeNode*> q;
        q.push(root);
        vector<int> res;
        int length=1;
        
        while(!q.empty()){
            int maxs=INT_MIN;
            for(int i=0; i<length; ++i){
                TreeNode* tmp=q.front();
                maxs=max(maxs, tmp->val);
                if(tmp->left) q.push(tmp->left);
                if(tmp->right) q.push(tmp->right);
                q.pop();
            }
            res.push_back(maxs);
            length=q.size();
        }
        return res;
    }
};


其实这种题都有两种方法,BFS和DFS都是可以的。

一开始想了一个DFS先找到树的深度,然后按深度给res分配长度,后来想想其实多加一个判断条件就可以不用找深度了。

class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        if(!root) return {};
        vector<int> res;
        dfs(res, root, 0);
        return res;
    }
    
    void dfs(vector<int>& res, TreeNode* root, int depth){
        if(!root) return ;
        if(depth >= res.size()) res.push_back(root->val);
        else if(root->val > res[depth]) res[depth] = root->val;
        dfs(res, root->left, depth + 1);
        dfs(res, root->right, depth + 1);
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值