简体   繁体   中英

Tree returning the maximum value

                        50
                       /  \
                      30  70 (( which should return 50+70=120 ))
int MyFunction(struct node *root){
    struct node *ptr=root;
    int leftsum=0;
    int rightsum=0;
    if(ptr==NULL){
        return;
    }
    else{

    MyFunction(ptr->left);
     leftsum=leftsum+ptr->key;
    MyFunctipn(ptr->right);
     rightsum=rightsum+ptr->key;
    return (root->key+max(leftsum,rightsum));
    } 
}

for that, I've written this code. Maybe it is wrong so please help me as I'm new in this field. I want to write a recursive code such a way that it compares two leaf node(left and right) and returns the maximum to the parent nood .

The recursive function should look something like this:

int getMaxPath(Node* root){
    // base case, We traveled beyond a leaf
    if(root == NULL){
        // 0 doesn't contribute anything to our answer
        return 0;
    }

    // get the max current nodes left and right children
    int lsum = getMaxPath(root->left);
    int rsum = getMaxPath(root->right);

    // return sum of current node value and the maximum from two paths starting with its two child nodes
    return root->value + std::max(lsum,rsum);

}

Full code:

#include <iostream>

struct Node{
    int value;
    Node* left;
    Node* right;

    Node(int val){
        value = val;
        left = NULL;
        right = NULL;
    }
};

// make a tree and return a pointer to it's root
Node* buildTree1(){
    /* Build tree like this:
            50
           /  \
          30  70
    */

    Node* root= new Node(50);
    root->left = new Node(30);
    root->right = new Node(70);
}

int getMaxPath(Node* root){
    if(root == NULL){
        // 0 doesn't contribute anything to our answer
        return 0;
    }

    int lsum = getMaxPath(root->left);
    int rsum = getMaxPath(root->right);

    return root->value + std::max(lsum,rsum);

}

int main() {
    using namespace std;

    Node* root = buildTree1();

    int ans = getMaxPath(root);

    cout<< ans <<endl;
    return 0;
}
int Sum(struct node *root)
    {

       if(root->left == NULL && root->right== NULL)
            return root->key;

        int lvalue,rvalue;


        lvalue=Sum(root->left);
        rvalue=Sum(root->right);

        return root->key+max(lvalue,rvalue);

    }

 int max(int r,int j)
 {
     if(r>j)
       return r;
     else
        return j;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM