[LeetCode] 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]

 

这道题让我们找二叉树每行的最大的结点值,那么实际上最直接的方法就是用层序遍历,然后在每一层中找到最大值,加入结果res中即可,参见代码如下:

 

解法一:

class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        if (!root) return {};
        vector<int> res;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int n = q.size(), mx = INT_MIN;
            for (int i = 0; i < n; ++i) {
                TreeNode *t = q.front(); q.pop();
                mx = max(mx, t->val);
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            res.push_back(mx);
        }
        return res;
    }
};

 

如果我们想用迭代的方法来解,可以用先序遍历,这样的话就需要维护一个深度变量depth,来记录当前结点的深度,如果当前深度大于结果res的长度,说明这个新一层,我们将当前结点值加入结果res中,如果不大于res的长度的话,我们用当前结点值和结果res中对应深度的那个结点值相比较,取较大值赋给结果res中的对应深度位置,参见代码如下:

 

解法二:

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

 

参考资料:

https://discuss.leetcode.com/topic/79241/simple-and-easy-understand-c-dfs-solution

 

LeetCode All in One 题目讲解汇总(持续更新中...)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值