二叉树的建立和基础操作 —— (三种遍历及分层打印)

#include
#include
#include
#include 
#include
#include 
using namespace std;
typedef struct BinaryTree
{
	char val;
	struct  BinaryTree *left;
	struct  BinaryTree *right;
}BinaryTree,*BitTree;

//******递归建立二叉树*****// 
//先建立根节点,再建立左子树,最后建立右子树
/***********
测试用例:
         a
    b         c
  #    d    #    e
     f   #     #   #
   #   #
输入:ab#df###c#e##  
***************/
int create_tree(BitTree &T)
{
	char val = getchar();
	if(val == '#')
	T = NULL;
	else  
	{
		T = new BinaryTree;
		T -> val = val;
		create_tree(T->left);
		create_tree(T->right);
	}
	return 0;
}

//*****前序递归遍历二叉树*****//
void Preorder(BitTree T)
{
	if(T)
	{
		cout<val<<" ";
		Preorder(T->left);
		Preorder(T->right);
	}
}

//*****中序递归遍历二叉树*****//
 void Midorder(BitTree T)
 {
 	if(T)
	{
		Midorder(T->left);
		cout<val<<" ";
		Midorder(T->right);
	}
 } 
 
//*****后序递归遍历二叉树*****// 
void behindorder(BitTree T)
{
	if(T)
	{
		behindorder(T->left);
		behindorder(T->right);
		cout<val<<" ";
	}
} 
 
//*****按层遍历*****//

//设置游标last,分层打印二叉树 
int layerorder_1(BitTree T)
{
	vector vec;
	vec.push_back(T);
	int cur = 0;
	int last = 1;
	while(cur < vec.size())
	{
		last = vec.size();//设置last游标 
		while(cur < last) //当last == cur时,退出循环,打印回车 
		{
			cout<val<<" ";
			if(vec[cur]->left)
				vec.push_back(vec[cur]->left);
			if(vec[cur]->right)
				vec.push_back(vec[cur]->right);
			cur++;
		}
		cout< q;
	q.push(T);
	do{
		temp = q.front();
		cout<val<<" ";
		q.pop();
		parentSize--; //每次pop一个节点,parentSize减去1 
		if(temp->left)
		{
			q.push(temp->left);
			childSize++;
		}
		if(temp->right)
		{
			q.push(temp->right);
			childSize++;
		}
		
		if(parentSize == 0) //当根节点出栈完毕时,表示本层可以输出回车了 
	   {                    //此时更新下一层parentSize,将childSize写入 
			parentSize = childSize; //childSize 赋值为0 
			childSize = 0;
			cout<
 
  

程序运行结果:

二叉树的建立和基础操作 —— (三种遍历及分层打印)_第1张图片

你可能感兴趣的:(数据结构与算法)