作者:雨狐
题目:输出二叉树中从根结点到值为x的结点的路径
描述
假设一棵二叉树采用二叉链存储结构存储,其中所有结点值均不相同。设计一个算法采用先序遍历方法求从根结点到值为x的结点时经历的所有节点(包括值为x的节点)。
输入
第一行:括号表示法的树字符串
第二行:指定值x
输出
采用先序遍历方法,从根结点到值为x的结点的路径
样例
样例输入
A(B(D,E(G,H)),C(,F(I)))
E
样例输出
A B D E
思路
在使用递归的先序遍历的基础上,使用全局变量flag,当遍历到目标元素x时,flag值发生改变,在递归函数内通过对flag值变化的判断,结束递归。
代码
#include <iostream>
using namespace std;
#define MaxSize 100
typedef char ElemType;
typedef struct tnode
{ ElemType data;
struct tnode *lchild,*rchild;
} BTNode;
void CreateBTree(BTNode * &bt,char *str)//由括号表示串创建二叉链
{ BTNode *St[MaxSize],*p=NULL;
int top=-1,k,j=0;
char ch;
bt=NULL; //建立的二叉树初始时为空
ch=str[j];
while (ch!='\0') //str未扫描完时循环
{ switch(ch)
{
case '(':top++;St[top]=p;k=1; break;//为左孩子结点
case ')':top--;break;
case ',':k=2; break; //为右孩子结点
default:p=new BTNode();
p->data=ch;p->lchild=p->rchild=NULL;
if (bt==NULL) //*p为二叉树的根结点
bt=p;
else //已建立二叉树根结点
{ switch(k)
{
case 1:St[top]->lchild=p;break;
case 2:St[top]->rchild=p;break;
}
}
}
j++;
ch=str[j];
}
}
void DestroyBTree(BTNode *&bt) //销毁二叉链
{ if (bt!=NULL)
{ DestroyBTree(bt->lchild);
DestroyBTree(bt->rchild);
delete bt;
}
}
// Traverse node and stop when x appears
int flag = 0;
void PreOrder_Find(BTNode *&bt, ElemType x)
{
if(bt != NULL && flag == 0)
{
cout<<bt->data<<" ";
if(bt->data == x) // 先打印目标值再改变flag值,下一次递归开始时结束递归
{
flag = 1;
}
PreOrder_Find(bt->lchild, x);
PreOrder_Find(bt->rchild, x);
}
}
int main()
{
char tree[MaxSize];
cin>>tree;
ElemType x;
cin>>x;
BTNode *bt;
CreateBTree(bt,tree);
PreOrder_Find(bt, x);cout<<endl;
DestroyBTree(bt);
return 0;
}
说明
此篇仅做交流学习之用,相关内容学习中,不能保证一定准确或者最优。还请多多指教。
参考链接
无