LeetCode 515. Find Largest Value in Each Tree Row [Medium]

原题地址

题目内容

这里写图片描述

题目分析

题目要求的是整棵树每一层最大的数。最开始想到的就是层序遍历,从上到下,从左到右遍历,把每一层最大的数存起来。后面参考了leetcode上面的discuss。发现还有另外一种做法,就是采用先序遍历,并且用depth来记录当前访问到第几层,由于每层只会有一个最大值,所以如果depth+1>result.size(),那么说明访问到了新的一层(因为depth是从0开始计数的),将当前的节点值push进result,result的size就变大了。否则就需要比较当前节点值与result[depth]值的大小了。
要注意一点的就是每一次访问的时候要注意空节点

代码实现

先序遍历
/**
 * 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> res;
    void findvalue(TreeNode* root, int depth){
        if(root == NULL){
            return;
        }
        if(res.size() < depth+1){
            res.push_back(root->val);
        }else{
            if(root->val > res[depth]){
                res[depth] = root->val;
            }
        }
        findvalue(root->left,depth+1);
        findvalue(root->right,depth+1);

    }
    vector<int> largestValues(TreeNode* root) {
        if(root == NULL){
            return res;
        }
        findvalue(root,0);
        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;
        queue<TreeNode*> p;
        if(root == NULL){
            return res;
        }
        p.push(root);
        while(!p.empty()){
            int size = p.size();
            int max = INT_MIN;//int整型当中最小的数
            for(int i = 0; i < size; i++){
                TreeNode*q = p.front();
                p.pop();
                if(q->val > max){
                    max = q->val;
                }
                if(q->left){
                    p.push(q->left);
                }
                if(q->right){
                    p.push(q->right);
                }
            }
            res.push_back(max);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值