递归和非递归方法建立二叉树

研三了,天天忙着找工作,细数来看过的算法也算多了,但是都是在不同的电脑上看的,而且都没有记录,因此开通此博客用于记录平时看书的笔记或者笔试题目,算法等的解释,写于此便于自己日后回顾和让其他在招工的同学们可以看到。

此文是在学习其他人算法的时候对非递归建立二叉树算法的优化,不一定是最好的,只是能够得出结果,希望有大牛看到此文章能够推荐更好的解法,或者对此算法提出优化意见。。谢谢

#include<iostream>
using namespace std;

typedef struct BiTreeNode
{
	char data;
	struct BiTreeNode *lChild,*rChild;
}*BiTree,BiTreeNode;

#define MAXSIZE  50

//BiTreeNode* stack[MAXSIZE]; //穿件二叉树节点栈
//int top =0;

//函数声明
BiTree CreateBiTree(); //递归建立二叉树
void PreOrderTraverse(const BiTree& root);
void InOrderTraverse(const BiTree& root);
void PostOrderTraverse(const BiTree& root);


BiTree CreateBiTreeNonRecur(char *str);//非递归建立二叉树
BiTreeNode* CreateNode(char* data); //创建二叉树节点;


int main()
{
	BiTree root;
	//cout<<"请输入根节点的值: ";
	//root = CreateBiTree();
	char str[] ="ABC@G@@@DE@@@";
	root = CreateBiTreeNonRecur(str);
	PreOrderTraverse( root);
	return 1;



}

BiTree CreateBiTree()
{
	char ch;
	cin>>ch;
	if(ch == '@')
		return NULL;
	BiTreeNode * tempNode = (BiTreeNode*)malloc(sizeof(BiTreeNode));
	if(tempNode == NULL)
	{
		cout<<"内存分配失败";
		return NULL;
	}
	tempNode->data = ch;
	cout<<"请输入节点 "<<ch <<" 的左节点: ";
	tempNode->lChild = CreateBiTree();
	cout<<"请输入节点 "<<ch <<" 的右节点: ";
	tempNode->rChild = CreateBiTree();
	return tempNode;
}

void PreOrderTraverse(const BiTree& root)
{
	if(root == NULL)
		return;
	cout<<root->data<<" ";
	PreOrderTraverse(root->lChild);
	PreOrderTraverse(root->rChild);
}


//非递归建立二叉树
BiTreeNode* CreateNode(char* data)  //创建一个节点
{
	BiTreeNode* temp = (BiTreeNode*)malloc(sizeof(BiTreeNode));
	temp->data = *data;
	temp->lChild = NULL;
	temp->rChild = NULL;
	return temp;
}
BiTree CreateBiTreeNonRecur(char* str)
{
	BiTreeNode* stack[MAXSIZE];
	int top = 0;
	if(*str == '\0')
	{
		cout<<"创建一个空的二叉树";
		return NULL;
	}
	BiTreeNode* root = NULL;
	BiTreeNode* tempRoot  = NULL; //当前指向节点
	BiTreeNode* temp =NULL;
	root = CreateNode(str);
	tempRoot = root;
	while(*str != '\0')
	{	str++;
		if(*(str-1)!= '@')  //建树过程中如果一直未碰到@符号,则持续建立左子树
		{					//并将节点压入栈中
			stack[top++] = tempRoot;
			if(*str != '@')    //判断当前节点是不是@节点,如果是的左子树为空
			{
				temp = CreateNode(str);
				tempRoot->lChild = temp;
				tempRoot = temp;
			}
			else
			{
				tempRoot->lChild =NULL;
			}

		}
		if(*(str-1) =='@' && top >0)  //若前一个节点是@,则出栈,建立右子树
		{
			tempRoot = stack[--top];
			if(*str != '@')//判断当前节点是不是@节点,如果是的右子树为空
			{
				temp = CreateNode(str);
				tempRoot->rChild = temp;
				tempRoot = temp;
			}
			else
				tempRoot->rChild =NULL;
		}
	}
	return root;
}


  • 10
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值