二叉树的操作——遍历2

根据前序遍历序列构建非空二叉树,使用二叉链表存储,然后分别按中序和后序顺序打印特定节点。
摘要由CSDN通过智能技术生成

Problem Description
按照给定的扩展二叉树前序遍历序列建立相应的非空二叉树,要求采用二叉链表进行存储表示,并按中序次序打印叶子结点,按后序次序打印度为2的分支结点。
Input
第一行为一个整数n,表示以下有n组数据,每组数据占一行,为扩展二叉树的前序遍历序列。
Output
每组输出占两行,叶子结点和分支结点各占一行,每两组输出之间有一换行。
Sample Input
3
AB#D##C##
AB##C#D##
ABD##E##C#F##
Sample Output
DC
A

BD
A

DEF
BA

#include<iostream>
using namespace std;
struct BiNode
{
	char data;
	BiNode *lchild,*rchild; 
};
BiNode *creat()
{
  BiNode *root;
  char ch;
  cin>>ch;
  if(ch=='#')
	  root=NULL;
  else
  {
	  root=new BiNode;
    root->data=ch;
	root->lchild=creat();
	root->rchild=creat();
  }
  return root;
}
void Release(BiNode *root)
{
	if(root!=NULL)
	{
	Release(root->lchild);
	Release(root->rchild);
	delete root;
	}
}
void PreOrder1(BiNode *root)
{

	if(root==NULL) return ;
	else
	{
     PreOrder1(root->lchild);
	 if(root->lchild&&root->rchild)
	 {cout<<root->data;}
	}
	 PreOrder1(root->rchild);

}
void PreOrder(BiNode *root)
{
	if(root==NULL) return;
	else
	{
       PreOrder(root->lchild);
	   PreOrder(root->rchild);
	   if(!root->lchild&&!root->rchild)
	 {cout<<root->data;}
	}
}

int main()
{
	int n;
	cin>>n;
	while(n--)
	{
    BiNode *root=creat();
	 PreOrder(root);
	 cout<<endl;
	 	 PreOrder1(root);
		 cout<<endl;
		 if(n!=0)
		 {
    cout<<endl;
		 }
		 Release(root);
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值