LeetCode 515. Find Largest Value in Each Tree Row (C++)

本文介绍两种算法来解决二叉树中每一层的最大值问题:一是使用层序遍历结合标识的方法;二是采用前序遍历(深度优先搜索)。通过这两种方式有效地找出二叉树各层的最大节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]

方法一:用vector + 2个标识进行层序遍历,好处:可以方便地在同一层内进行遍历。

/**
 * 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> solution;
        vector<TreeNode*> nVector;
        
        if (!root) return solution;
        int cur = 0;
        int end = 0;
        nVector.push_back(root);
        
        while(cur < nVector.size())
        {
            end = nVector.size();
            int max = nVector[cur]->val;
            while (cur < end) {
                if (nVector[cur]->left) nVector.push_back(nVector[cur]->left);
                if (nVector[cur]->right) nVector.push_back(nVector[cur]->right);
                max = (max < nVector[cur]->val) ? nVector[cur]->val : max;
                ++cur;
            }
            solution.push_back(max);
        }
        return solution;
    }
};

方法二:前序遍历(深度优先搜索)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值