C++二叉树的层次构建、先序构建、层次遍历、先序遍历等

先序构建二叉树,层次遍历二叉树

//层次构建二叉树,先序遍历二叉树
//输入样例:12345000000 先序输出 12453
#include <bits/stdc++.h>

using namespace std;

struct Treenode{
	char data;
	Treenode *lchild;
	Treenode *rchild;
	Treenode(char c):data(c),lchild(NULL),rchild(NULL){}
};

Treenode *creat()//层次构建树
{
	queue<Treenode*>myqueue;
	char x;
	cin>>x;
	if(x=='0')  return NULL;
	Treenode* root=new Treenode(x);
	myqueue.push(root);
	while(!myqueue.empty())
	{
		Treenode *T=myqueue.front();
		myqueue.pop();
		char y;
		cin>>y;
		if(y=='0')   T->lchild=NULL;
		else
		{
			T->lchild=new Treenode(y);
			myqueue.push(T->lchild);
		}
		char z;
		cin>>z;
		if(z=='0')  T->rchild=NULL;
		else
		{
			T->rchild=new Treenode(z);
			myqueue.push(T->rchild);
		}
	}
	return root;
}

void preorder(Treenode* root)//先序输出
{
	if(root==NULL) return ;
	cout<<root->data<<endl;
	preorder(root->lchild);
	preorder(root->rchild);
	return ;
}

int main()
{
	Treenode *root=creat();
	if(root==NULL) printf("NULL\n");
	printf("先序序列:\n");
	preorder(root);
	return 0;
}`

/*****************************************************/
先序构建二叉树,层次遍历二叉树

/*
先序构建二叉树,层次遍历二叉树
二叉树遍历:abc##de#g##f### 
输出:a b c d e f g
*/
#include <bits/stdc++.h> 


using namespace std;

struct Treenode{
	char data;
	Treenode* leftchild;
	Treenode* rightchild;
	Treenode(char d):data(d),leftchild(NULL),rightchild(NULL){}
};

int i;

Treenode* Creattree(string str)//先序构建树
{
	char c=str[i++];  
	if(c=='#') return NULL;
	Treenode* T=new Treenode(c);
	T->leftchild=Creattree(str);
	T->rightchild=Creattree(str);
	return T;
}

void BFS(Treenode *T)//层次输出
{
	if(!T) return ;
	queue<Treenode*>myqueue;
	myqueue.push(T);
	while(!myqueue.empty())
	{
		Treenode* c=myqueue.front();
		myqueue.pop();
		cout<<c->data<<endl;
		if(c->leftchild) myqueue.push(c->leftchild);
		if(c->rightchild) myqueue.push(c->rightchild);
	}
	return ; 
} 

int main()
{
	string str;
	while(cin>>str)
	{
		i=0;
		Treenode* T=Creattree(str);
		BFS(T);
	}
	return 0;
}
发布了8 篇原创文章 · 获赞 0 · 访问量 70

猜你喜欢

转载自blog.csdn.net/weixin_46274692/article/details/105031067