现在的位置: 首页 > 综合 > 正文

数据结构之二叉树的建立与遍历

2013年08月01日 ⁄ 综合 ⁄ 共 1532字 ⁄ 字号 评论关闭

已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后方式遍历二叉树最后求出叶子节点个数和二叉树深度

#include<iostream>
#include<queue>
#include <cstdlib>
#include <cstdio>
using namespace std;
typedef struct BiNode
{
	char data;
	struct BiNode *left;
	struct BiNode *right;
}BiNode, *BiTree;
int sum = 0;
void CreateBinaryTree(BiTree &T)//二叉树建立   abc,,de,g,,f,,,
{
	//T = (BiNode*) malloc (sizeof(BiNode));
	T = new BiNode;
	cin >> T->data;
	if(T->data == ',') 
	{
		T = NULL; 
	}
	if(T != NULL)
	{
		CreateBinaryTree(T->left);
		CreateBinaryTree(T->right);
	}
}
void PreOrder(BiTree T)//前序遍历
{
	if(T != NULL)
	{
		cout << T->data;
		PreOrder(T->left);
		PreOrder(T->right);
	}
}
void InOrder(BiTree T)//中序遍历
{
	if(T != NULL)
	{
		InOrder(T->left);
		cout << T->data;
		InOrder(T->right);
	}
}
void PostOrder(BiTree T)//后序遍历
{
	if(T != NULL)
	{
		PostOrder(T->left);
		PostOrder(T->right);
		cout << T->data;
	}
}
void LevOrder(BiTree T)//层次遍历
{
	if(T != NULL)
	{
		BiTree p = T;
		queue<BiTree>que;
		que.push(p);
		while(!que.empty())
		{
			p = que.front();
			cout << p->data;
			que.pop();
			if(p->left != NULL)
			{
				que.push(p->left);
			}
			if(p->right != NULL)
			{
				que.push(p->right);
			}
		}
	}
}
int Size(BiTree T)//计算二叉树节点数
{
	if(T)
	{
		if(T->left == NULL && T->right == NULL)
		{
			sum++;
		}
		Size(T->left);
		Size(T->right);
	}
	return sum;
}
int Deep(BiTree T)//计算二叉树深度
{
	int m, n;
	if(T == NULL) return 0;
	m = Deep(T->left);
	n = Deep(T->right);
	if(m > n) return m + 1;
	else return n + 1;
}
int main(void)
{
	BiTree T;
	CreateBinaryTree(T);

	cout << "前序遍历结果为:" << endl;
	PreOrder(T);
	cout << endl << endl;

	cout << "中序遍历结果为:" << endl;
	InOrder(T);
	cout << endl << endl;

	cout << "后序遍历结果为:" << endl;
	PostOrder(T);
	cout << endl << endl;

	cout<<"层次遍历结果为:"<<endl;
	LevOrder(T);
	cout << endl << endl;

	cout << "二叉树叶节点个数为:" << Size(T)<<endl;
	cout << "二叉树深度数为:" << Deep(T) << endl;
	system("pause");
	return 0;
}


抱歉!评论已关闭.