题记:程序意图如题。查找路径的方法很简单,就是对后序遍历算法稍加改变。从根结点到任一给定结点的逆向路径(即从任一给定结点到根结点的路径)一定是符合后序遍历序列的保序性,即在逆向路径中若A在B的后面,则在后序遍历序列中A也一定在B的后面,反之亦然。基于这个特点,我们可以得到这样的结论:逆向路径一定是后序遍历序列中去掉一些结点后的序列。至于去掉哪些结点,很简单,只要在后序遍历序列中加上一个限制条件:逆向路径中结点A的下一个结点一定是A的父结点。基于这个设计思想,写出了如下程序:
源代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define type int
#define LEN 20
#define MAXPATH 20
typedef struct tree
{
type data;
struct tree* left;
struct tree* right;
}tree;
tree* pre_creat(void)
{
tree* root=(tree*)malloc(sizeof(tree));
if(root==NULL)
{
printf("creat root error/n");
exit(-1);
}
type data;
scanf("%d",&data);
if(data!=0)
{
root->data=data;
root->left=pre_creat();
root->right=pre_creat();
}
else
{
root=NULL;
}
return root;
}
int *find_path(tree* root,int node)
{
if(root==NULL)
{
printf("tree is NULL/n");
exit(-1);
}
int *path=(int*)malloc(sizeof(int)*MAXPATH);
memset(path,0,sizeof(int)*MAXPATH);
int FoundNeededNode=0;
int *BaseAddr=path;
*path=node;
++path;
tree *stack[LEN]={NULL,};
int status[LEN]={0};
int top=-1;
stack[++top]=root;
status[top]++;
while(top!=-1)
{
if(status[top]==1)
{
if(stack[top]->left!=NULL)
{
stack[top+1]=stack[top]->left;
status[top]++;
status[top+1]=1;
top++;
}
else
status[top]++;
}
else if(status[top]==2)
{
if(stack[top]->right!=NULL)
{
stack[top+1]=stack[top]->right;
status[top]++;
status[top+1]=1;
top++;
}
else
status[top]++;
}
else if(status[top]==3)
{
if(stack[top]->data==node)
{
FoundNeededNode=1;
}
if(FoundNeededNode==1)
{
if((stack[top]->left!=NULL&&stack[top]->left->data==*(path-1))/
||(stack[top]->right!=NULL&&stack[top]->right->data==*(path-1)))
{
*path=stack[top]->data;
if(*path==root->data)
return BaseAddr;
if(*path==root->left->data)
{
path++;
*path=root->data;
return BaseAddr;
}
++path;
}
}
--top;
}
}
if(FoundNeededNode==0)
return NULL;
else
return BaseAddr;
}
int main(void)
{
tree* root=pre_creat();
if(root==NULL)
{
printf("tree is null/n");
exit(-1);
}
printf("input the node:");
int data;
scanf("%d",&data);
int *path=find_path(root,data);
int *head=path;
if(path==NULL)
printf("no such node/n");
else
{
printf("path is:");
while(*path!=0)
++path;
while(--path>=head)
printf("%d->",*path);
}
printf("/n");
return 0;
}
输入举例:(创建如下图所示的二叉树,搜索从根结点6到结点4的路径)
6 2 1 0 0 5 3 0 4 0 0 0 8 0 0
input the node:4
path is:6->2->5->3->4->