求路径(二叉树)

1、题目:

 Problem Description

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

 Input

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




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值