LC1161. Maximum Level Sum of a Binary Tree

https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/

  • 진짜 오랜만에 짜본 BFS
  • 멍 하게 짜니까 더 오래걸린다.
  • Stack이 터질까봐 DFS로 안짰는데 -_- DFS로도 풀리는듯
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * 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:
    int maxLevelSum(TreeNode* root) {
        queue<TreeNode*> q;
        q.push(root);
        
        int sz, sum = 0, ans = root->val, level = 1, anslev = 1;
        while(sz = q.size()) {
            sum = 0;
            for(int i = 0; i < sz; i++) {
                TreeNode* cur = q.front(); q.pop();
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
                sum += cur->val;
            }
            if(ans < sum) {
                ans = sum;
                anslev = level;
            }
            level++;
        }
        return anslev;
    }
};