recursion - 返回最大值的树

标签 recursion data-structures graph tree

                        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));
    } 
}

为此,我编写了这段代码。也许这是错误的,所以请帮助我,因为我是这个领域的新手。 我想写一个递归代码,它比较两个叶节点(左和右)并将最大值返回给父节点 .

最佳答案

递归函数应如下所示:

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);

}

完整代码:
#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;
}

关于recursion - 返回最大值的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645027/

相关文章:

将递归 C 函数转换为 ARM 程序集?

c# - 递归函数的顺序编号?例如2, 2.1, 2.1.1, 2.2, 2.2.1

java - 为什么不能将 LinkedList 的最后一个节点设置为 null?

c - 为什么这段代码无法执行呢?

algorithm - 核外连通分量算法

c# - 如何从表示 C# 或 VB 中的目录结构的字符串列表创建集合

objective-c - 在不相交的集合数据结构中实现路径压缩?

algorithm - 以编程方式将节点分配给分层树/网络

c - 确定函数原型(prototype)

java - 搜索分散 3D 图的 Java 示例