求路径(二叉树)

来源:互联网 发布:诸城明诚学校网络平台 编辑:程序博客网 时间:2024/06/06 00:51

1、题目:

 Problem Description

假设有一棵二叉树,其结点的值是字符型,该二叉树采用二叉链表存储方式表示。输入其扩展二叉树的前序遍历序列,用于建立该二叉树,并且假设p所指结点为一给定的结点x。现要求求出根结点到p所指结点x之间的路径。我们假设这棵二叉树不为空树。

 Input

第一行为一个整数n,表示有n组测试实例。
每组测试实例占两行:
第一行为一字符串,表示一棵扩展二叉树的前序遍历序列;
第二行为一字符,表示给定的结点x。

 Output

输出根结点到结点x的路径。

 Sample Input

2AB#D##C##DABD##E##C#F##F

 Sample Output

A->B->DA->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;}




原创粉丝点击