【LeetCode-树】在每个树行中找最大值

题目描述

您需要在二叉树的每一行中找到最大的值。
示例:

输入: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

输出: [1, 3, 9]

题目链接: https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/

思路

这题就是二叉树的层次遍历,在遍历每层时记录最大值即可。代码如下:

/**
 * 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==nullptr) return {};

        vector<int> ans;
        queue<TreeNode*> q;
        q.push(root);
        int curLevelNums = 1;   // 当前层的节点数
        int nextLevelNums = 0;  // 下一层的节点数
        int curMax = 0x80000000;
        int cur = root->val;
        while(!q.empty()){
            TreeNode* curNode = q.front(); q.pop();
            curLevelNums--;
            cur = curNode->val;
            curMax = max(curMax, cur);
            if(curNode->left!=nullptr){
                q.push(curNode->left);
                nextLevelNums++;
            }
            if(curNode->right!=nullptr){
                q.push(curNode->right);
                nextLevelNums++;
            }
            if(curLevelNums==0){
                curLevelNums = nextLevelNums;
                nextLevelNums = 0;
                ans.push_back(curMax);
                curMax = 0x80000000;
            }
        }
        return ans;
    }
};
  • 时间复杂度:O(n)
    n为树中的节点个数。
  • 空间复杂度:O(m+h)
    m为每层的最大节点个数,h为树高。

猜你喜欢

转载自www.cnblogs.com/flix/p/12715563.html