"Hello World!" in C

  • + 0 comments
    //Maximum Level Sum in a Binary Tree
    #include <iostream>
    #include <queue>
    using namespace std;
    
    struct Node {
        int val;
        Node *left, *right;
        Node(int x) : val(x), left(nullptr), right(nullptr) {}
    };
    
    int maxLevelSum(Node* root) {
        if (!root) return 0;
        queue<Node*> q;
        q.push(root);
        int maxSum = root->val;
        while (!q.empty()) {
            int levelSum = 0, size = q.size();
            for (int i = 0; i < size; i++) {
                Node* node = q.front();
                q.pop();
                levelSum += node->val;
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
            maxSum = max(maxSum, levelSum);
        }
        return maxSum;
    }
    
    int main() {
        Node* root = new Node(1);
        root->left = new Node(2);
        root->right = new Node(3);
        root->left->left = new Node(4);
        root->left->right = new Node(5);
        root->right->right = new Node(8);
        cout << maxLevelSum(root);
        return 0;
    }