515. Find Largest Value in Each Tree Row**

515. Find Largest Value in Each Tree Row**

https://leetcode.com/problems/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]

C++ 实现 1

逻辑其实和 513. Find Bottom Left Tree Value** 没啥区别. 层序遍历.

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 size = q.size();
            int imax = q.front()->val;
            while (size --) {
                auto r = q.front();
                q.pop();
                imax = max(imax, r->val);
                if (r->left) q.push(r->left);
                if (r->right) q.push(r->right);                
            }
            res.push_back(imax);
        }
        return res;
    }
};

C++ 实现 2

这道题其实也可以用 DFS 来实现, 使用 d 来记录当前访问的深度; 如果 d == res.size(), 说明此时访问的是第 d 层的第一个节点 (就是说第一次到第 d 层), 将该节点的值加入到 res 中; 之后如果再到第 d, 那么更新 res[d] 即可.

class Solution {
private:
    vector<int> res;
    void dfs(TreeNode *root, int d) {
        if (!root) return;
        if (d == res.size()) res.push_back(root->val);
        else res[d] = max(res[d], root->val);
        dfs(root->left, d + 1);
        dfs(root->right, d + 1);
    }
public:
    vector<int> largestValues(TreeNode* root) {
        dfs(root, 0);
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值