[LeetCode-Tree] Find the maximum value in each tree row

Title description

You need to find the largest value in each row of the binary tree.
Examples:

输入: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

输出: [1, 3, 9]

Title link: https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/

Ideas

This problem is the hierarchical traversal of the binary tree , and the maximum value can be recorded when traversing each layer. code show as below:

/**
 * 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;
    }
};
  • Time complexity: O (n)
    n is the number of nodes in the tree.
  • Space complexity: O (m + h)
    m is the maximum number of nodes in each layer, and h is the tree height.

Guess you like

Origin www.cnblogs.com/flix/p/12715563.html