列出并计算二叉树从根结点到叶结点的权重最大的路径

List and count the most weight path from the root to the leafs of a binary tree

本文关键字:结点 权重 路径 计算 二叉树 叶结点      更新时间:2023-10-16

我必须返回节点的数量和从根到某个叶子的权重最大的路径的权重。注意这个树不是一个二叉搜索树,它是无序的。

即:

     6
   /   
  9     6
 /     / 
3     1   19

然后,我必须返回整数6 + 6 + 19 = 31并打印节点6 - 6 - 19

这是我的代码:
int heavierPath ( Node * tree ) {
    if ( ! tree ) return 0;
    int leftWeight = heavierPath( tree->left );
    int rightWeight= heavierPath( tree->right );
    if ( leftWeight >= rightWeight ) {
        if ( tree->left )
            cout << tree->left->value << endl;
        return tree->value + leftWeight;
    }
    else {
        cout << tree->right->value << endl;
        return tree->value + rightWeight;
    }
};

和结果是31,但我看到所有的节点值在终端。

如何修复它并只打印位于较重路径中的元素?(递归)

谢谢!

在我编辑它之后,它似乎工作了。

以:http://ideone.com/OGcyun为例。

你的问题:

考虑这个图:

     6
   /   
  9     6
 /     / 
3     1   19

为每个节点编号:

     0
   /   
  1     2
 /     / 
3     4   5

考虑您在节点1的情况。你要求更好的路径,得到leftWeight = 3rightweight = 0,你打印"更好"的路径,3。这不是最终结果的一部分。

解决方案

为了解决这个问题,我在retstruct中传递了额外的数据,其中包含path(到目前为止最重的路径),value(使打印更容易),sum(确定更好的路径)。

然后我将函数改为:

retstruct* heavierPath ( Node * tree ) {
    if ( ! tree ) return new retstruct();
    //Get both paths
    retstruct* leftWeight = heavierPath( tree->left );
    retstruct* rightWeight= heavierPath( tree->right );
    //Find the "heavier" path
    if ( leftWeight->sum >= rightWeight->sum ) {
        //Delete lighter path
        delete_retstruct(rightWeight);
        //Pass up the better path with the correct data
        return new retstruct(leftWeight, tree->value, tree->value + leftWeight->sum);
    } else {
        //Delete lighter path
        delete_retstruct(leftWeight);
        //Pass up the better path with the correct data
        return new retstruct(rightWeight, tree->value, tree->value + rightWeight->sum);
    }
};

添加delete_retstruct函数:

void delete_retstruct (retstruct* path) {
    if (path->path == NULL) {
        delete path;
    } else {
        delete_retstruct(path->path);
    }
}

和printPath函数:

void printPath (retstruct* path) {
    if (path->path != NULL) {
        std::cout << " - " << path->value;
        printPath(path->path);
    }
}

这样使用:

retstruct* path = heavierPath(tree);
//Print sum
std::cout << "Sum: " << path->sum << std::endl;
//Print path
std::cout << "Path: " << path->value;
printPath(path->path);
std::cout << std::endl;
输出:

Sum: 31
Path: 6 - 6 - 19

我的建议是制作两个函数,第一个函数将找到从根到它的路径最大的叶子。假设你有一个指向这个叶子的指针,这里是打印路径的函数。

bool print(struct node *r, struct node *leaf)
{
    if (r == NULL)
        return false;
    //will print if it is leaf or on path to leaf
    if (r == leaf || print(r->left, leaf) || print(r->right, leaf) )
    {
        printf("%d ", r->val); // this will print in reverse order
                               // if you want to print from root, store values in stack and then print the value after the function call
        return true;
    }
    return false;
}

问题是您将打印节点与查找和混合在一起。后者必须访问所有子节点,而打印只需访问路径中的子节点。下面是一个可能的解决方案:

#include <iostream>
#include <unordered_map>
struct Node
{
    Node(int value = 0, Node* left = nullptr, Node* right = nullptr) :
        value{value},
        left{left},
        right{right}
    {}
    int value;
    Node* left;
    Node* right;
};
std::unordered_map<Node*, int> map;
int pathSum(Node* node)
{
    if (node == nullptr)
    {
        return 0;
    }
    else if (map.find(node) == map.end())
    {
        return (pathSum(node->left) > pathSum(node->right)) 
                ? (map[node] = node->value + pathSum(node->left)) 
                : (map[node] = node->value + pathSum(node->right));
    }
    else
    {
        return map[node];
    }
}
void printPath(Node* node)
{
    if (node == nullptr)
    {
        return;
    }
    std::cout << node->value << std::endl;
    if (pathSum(node->left) > pathSum(node->right))
    {
        printPath(node->left);
    }
    else
    {
        printPath(node->right);
    }
}
int main() {
    Node* tree = new Node(6, 
                             new Node(9,
                                         new Node(3)),
                             new Node(6,
                                         new Node(1),
                                         new Node(19)));
    std::cout << "Biggest Sum: " << pathSum(tree) << std::endl;
    std::cout << "Biggest Sum Path: " << std::endl;
    printPath(tree);
    return 0;
}

在这样的递归解决方案中,缓存结果因此std::unordered_map是一个好主意。代码已在Ideone进行了测试。