找到叶子的路径等于总和(不是BST)

时间:2013-05-26 12:41:58

标签: c binary-tree

我正在尝试在C中编写一个递归函数,它接收二叉树中的根,并检查是否存在等于给定和的pathtoleaf。例如,它接收以下树中的第一个节点:

          1

   2              3

5       10       4    20

                            2

以下是PathToLeaf的示例:

  • 1⟶2⟶10
  • 2⟶5
  • 20⟶2

以下不是PathToLeaf:

  • 1⟶2
  • 1⟶3⟶20

如果存在路径,则该函数应返回1;如果不是,它应该返回0。

在这棵树中,如果sum = 12,那么函数应该返回1,因为路径为2⟶10;如果sum = 4,那么函数应该返回0,因为唯一的路径(1⟶3)不会以叶子结束。

我的大问题是我只能管理一个检查roottoleaf路径的函数。

1 个答案:

答案 0 :(得分:1)

如果您有一个函数roottoleaf(const BST *tree, int target),那么您的pathtoleaf(const BST *tree, int target)函数可以轻松实现,不是,使用适当的遍历树吗?

int pathtoleaf(const BST *tree, int target)
{
    if (roottoleaf(tree, target))
        return 1;
    else if (pathtoleaf(tree->left, target))
        return 1;
    else if (pathtoleaf(tree->right, target))
        return 1;
    else
        return 0;
}