您的位置:首页 > 其它

在二元树中找出和为某一值的所有路径

2015-02-09 16:13 309 查看
输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。

打印出和与输入整数相等的所有路径。

例如输入整数22 和如下二元树

10

/ \

5  12

/ \

4   7

则打印出两条路径:10, 12 和10, 5, 7。


思路:

1、当访问到某一节点时,把该结点的值添加到当前和变量,且把该结点压入栈中。

2、若结点为叶子结点,且当前和变量==期望的和,则打印栈中的结点值,即为所需的路径。

3、若结点不是叶子结点,继续访问它的左孩子结点,访问它的右孩子结点。

4、删除该结点。包括从当前和变量中减去结点值,从栈中弹出结点值。此时,已回到父结点

/**
在二元树中找出和为某一值的所有路径
** author :xiaozhi xiong
** date:2014-02-09
**/
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
struct node
{
int data;
struct node *lNode;
struct node *rNode;
};
struct node *head;

struct node *createTree(int a[],int len)
{
struct node *curNode,*nextNode,*newNode;
int i=1;
if(len<=0)
return NULL;
head=(struct node *)malloc(sizeof(struct node *));
head->data =a[0];
head->lNode =NULL;
head->rNode =NULL;
while(i<len)
{
newNode=(struct node *)malloc(sizeof(struct node *));
newNode->data =a[i];
newNode->lNode =NULL;
newNode->rNode =NULL;

curNode=head;
if(head->data>a[i])
nextNode=head->lNode ;
else nextNode=head->rNode ;

while(nextNode)
{
curNode=nextNode;
if(curNode->data >a[i])
nextNode=curNode->lNode ;
else
nextNode=curNode->rNode ;
}

if(curNode->data >a[i])
curNode->lNode =newNode;
else
curNode->rNode =newNode;
i++;
}
return head;
};
int path[10];
int sum;
int num;
void FindPath(struct node *p,int value)
{
int i;
if(p)
{
if(p->lNode==NULL&&p->rNode==NULL)
{
sum+=p->data ;
num++;
path[num]=p->data ;
if(sum==value)
{
for(i=0;i<=num;i++)
printf("%d  ",path[i]);
}
num--;
sum-=p->data;
}
else
{
sum+=p->data ;
num++;
path[num]=p->data ;
FindPath(p->lNode,value);
FindPath(p->rNode ,value);
}
}
}

int main(void)
{
int a[]={10,5,4,7,12};
head=createTree(a,5);
path[0]=head->data ;
sum=path[0];
num=0;
FindPath(head->lNode,22);
sum=path[0];
num=0;
printf("\n");
FindPath(head->rNode,22);

getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: