求tree中节点之间路径总和等于给定数值的算法

原题目:

Given a tree (any tree, in this code, i define the tree as a binary tree) and a integer value, please calculate and print the nodes if their total case is equal the given integer value.   Fg.


treehead-> A{1}

                     /    \

               B{2}  C{1}

                /           \

             D{0}     E{2}

          /                \

          F{1} 


the function signature is blow: 
void calculatePath(node* treehead, int cost)

if given tree and integer as below:  
calculatePath(treehead, 4)
 this function will print out:
    F + D + B + A = 4
   E + C + A = 4

if given integer is : 2, the print out will be like this:
  D + B = 2
  C + A = 2 


Here is my implementation for your reference: 
struct node 
{
node* parent;
node* left;
node* right;
char name;
int cost;
};

void printNodesBetween(node* parent, node* child, int cost)
{
if (child == NULL || parent == NULL) return;

node* tempChild = child;
while (tempChild!= parent )
{
printf("%c + ", tempChild->name);
tempChild = tempChild->parent;
}
printf ("%c = %d \n", tempChild->name, cost);
}

void calculatePathBetween(node* parent, node* child, int cost)
{
if (child == NULL)
return;

node* tempParent = parent;
int totalCost = child->cost;
while (tempParent != NULL)
{
totalCost += tempParent->cost;
if (totalCost == cost)
{
printNodesBetween(tempParent, child, cost);
}

tempParent = tempParent->parent;
}

calculatePathBetween(child, child->left, cost);
calculatePathBetween(child, child->right, cost);
}

void calculatePath(node* treehead, int cost)
{
if (treehead == NULL)
{
return;
}

calculatePathBetween(treehead, treehead->left, cost);
calculatePathBetween(treehead, treehead->right, cost);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值