To the fullest layer elements and ---- leetcode week race 150_1002

Subject description:

You root for the root node of a binary tree. Provided root node of a binary tree is located in the first layer, and the child nodes of the root located on the 2nd, and so on.
Please identify the elements of the inner layer and the largest of the several layers (probably only one) of the layer number, and returns the smallest one.

Example:

Input: [1,7,0,7, -8, null, null]
Output: 2
Explanation:
The first layer of each element is the sum of 1,
the second layer of each element is the sum of 7 + 0 = 7,
the third layer the elements and -8 to + 7 = -1,
so we return layer number of the second layer, the inner layer element it is the sum of the maximum.

prompt

  1. Number of nodes in the tree is interposed 1 和 10^4between
  2. -10^5 <= node.val <= 10^5

Ideas:

  • Using the queue, the sequence of the binary tree traversal, and recording each node, ans updated gradually to a maximum and where the number of layers
  • Variables can be used, the recording layer of the number of nodes, each for use of one loop access node, can achieve the purpose of statistical

Specific code as follows:

class Solution {
public:
    int ans =  0;int anshe = -2147483648;//ans层数与ans层和
    int cenghe; int curceng;
    queue<TreeNode*> que;
    int maxLevelSum(TreeNode* root) {
        if(!root)return 0;
        int len =1;int next = 0;curceng = 0;//当前层个数,下一层节点个数,当前在第几层。
        que.push(root);
        while(que.size()){
            cenghe = 0;//当前层的和
            curceng ++;//当前在第几层
            next = 0;//下一层个数
            for(int i  = 0 ; i < len;i++){
                TreeNode* t = que.front();que.pop();
                cenghe += t->val;
                if(t->left){que.push(t->left);next++;}
                if(t->right){que.push(t->right);next++;}
            }
            len = next;
            if(cenghe > anshe){
                ans = curceng;
                anshe = cenghe;
            }
        }
        return ans;
    }
};

Guess you like

Origin www.cnblogs.com/zhangxiaomao/p/11372753.html