1、题目:
Problem Description
假设有一棵二叉树,其结点的值是字符型,该二叉树采用二叉链表存储方式表示。输入其扩展二叉树的前序遍历序列,用于建立该二叉树,并且假设p所指结点为一给定的结点x。现要求求出根结点到p所指结点x之间的路径。我们假设这棵二叉树不为空树。
Input
第一行为一个整数n,表示有n组测试实例。
每组测试实例占两行:
第一行为一字符串,表示一棵扩展二叉树的前序遍历序列;
第二行为一字符,表示给定的结点x。
每组测试实例占两行:
第一行为一字符串,表示一棵扩展二叉树的前序遍历序列;
第二行为一字符,表示给定的结点x。
Output
输出根结点到结点x的路径。
Sample Input
2 AB#D##C## D ABD##E##C#F## F
Sample Output
A->B->D A->C->F
2.参考代码:
#include <iostream>
#include <stack>
using namespace std;
struct BiNode{
char data;
BiNode* lchild,* rchild,* fa;
}; //加一个指向父节点的指针
BiNode* Creat(BiNode* root){
char ch;
cin>>ch;
if(ch=='#')
root=NULL;
else{
root=new BiNode;
root->data=ch;
root->fa=NULL; ///初始化指向父节点的指针为空
root->lchild=Creat(root->lchild); ///建立左孩子
if(root->lchild) ///如果左孩子不为空
root->lchild->fa=root; ///记下左孩子的父亲
root->rchild=Creat(root->rchild); ///右孩子同理
if(root->rchild)
root->rchild->fa=root;
}
return root;
}
stack<char> st; ///用一个栈来保存路径
BiNode* tmp; ///工作指针
void Query(BiNode* root,char x){
if(root==NULL)
return ;
else{
if(root->data==x) ///如果工作指针找到所给结点
{
tmp=root; ///记下该节点
return ;
}
Query(root->lchild,x);
Query(root->rchild,x);
}
}
int main()
{
char x;
int n;
cin>>n;
while(n--)
{
BiNode* root=Creat(NULL);
cin>>x;
Query(root,x);
while(tmp->fa){
st.push(tmp->data); ///结点入栈
tmp=tmp->fa; ///指针下移
}
st.push(root->data); ///根节点入栈
bool flg=false;
while(!st.empty()){
if(flg)
cout<<"->";
cout<<st.top();
st.pop();
flg=true;
}
cout<<endl;
}
return 0;
}