Quick actions

cmd+k|ctrl+k

Navigation

Languages

Largest Subtree Sum

Snippet info

Language

Cpp

Visibility

public

Author

amangoyal1727

Created

2021-02-02T19:33:56Z

Updated

2021-02-02T19:34:36Z

#include <bits/stdc++.h> 
using namespace std;
struct Node {
    int data;
    Node * left;
    Node * right;
};

Node * newNode(int data ){
    Node* temp = new Node();
    (*temp).data = data;
    (*temp).left = NULL;
    (*temp).right = NULL;
    
    return temp;
}

int maxSum(Node *root , int &ans){
    
    if(root == NULL){
        return 0;
    }
    
    int sum = root->data + maxSum(root->left,ans) + maxSum(root->right,ans);
    
    ans = max (sum ,ans);
    
    return sum;
    
}



int main() {
    Node * root = NULL;
    root = newNode(1);
    root->left = newNode(-2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(-6);
    root->right->right = newNode(2);
    
    int ans = INT_MIN;
    maxSum(root, ans);
    
    cout<<ans;
    
    
    
    
    
    return 0;
}
INFO