我正在尝试用C写一个递归函数,它接收二叉树中的根,并检查是否存在等于给定和的pathtolleaf。例如,它接收以下树中的第一个节点:
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(const BST *tree, int target)
,你的pathtoleaf(const BST *tree, int target)
函数很容易跟随,不是吗,使用合适的树遍历?
int pathtoleaf(const BST *tree, int target)
{
if (tree == NULL)
return 0;
else 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;
}
2021-07-04:更新以覆盖tree
为NULL的情况