二叉树的建立(多种方法)

6 篇文章 0 订阅
5 篇文章 0 订阅

非递归实现

typedef struct BiTNode{
	char data;
	BiTNode* lchild, *rchild;
}BiTree;

//非递归实现二叉树的建立
BiTree* BiTreeCreate(){
	BiTree* Q[100];
	char ch;
	int front, rear;
	BiTree* s, *root;
	root = NULL;
	front = 1;
	rear = 0;
	cout << "请完全按照二叉树的编号顺序输入节点序列:" << endl;
	cout << "空节点用@表示,输入序列以#结束" << endl;
	ch = getchar();
	while (ch != '#')
	{
		s = NULL;
		if (ch != '@')
		{
			s = new BiTree();
			s->data = ch;
			s->lchild = NULL;
			s->rchild = NULL;
		}
		rear++;
		//这儿无论节点是否为空都放入数组
		Q[rear] = s;
		if (rear == 1)
			root = s;
		else
		{
			//若此节点为空则不需要对根节点的左右孩子赋值,因为创立节点时就把左右孩子节点默认为空
			if (s != NULL&&Q[front] != NULL)
			{
				if (rear % 2 == 0)//rear为偶数,说明此节点为根节点的左子树
					Q[front]->lchild = s;
				else//rear为奇数,说明此节点为根节点的右子树
					Q[front]->rchild = s;
			}
			//rear为奇数,说明一颗最基本二叉树(根,左右孩子)完成
			//此时使front+1,指向数组中下一位元素,进行它的二叉树建立
			if (rear % 2 == 1)
			{
				front++;
			}
		}
		
		ch = getchar();
	}
	
	return root;
}

递归实现:

struct tree{
	int data;
	tree* lchild, *rchild;
};
void BTree::create(tree* &s){
	int n;
	cin >> n;
	if (n == 0)
		s = NULL;
	else{
		s = new tree();
		s->data = n;
		/*BTree类中的root
		if (root == NULL)
			root = s;
		*/
		create(s->lchild);
		create(s->rchild);
	}
}

void BTree::Build(int x,tree* &bt){
		bt = new tree();
		bt->data = x;
		if (root == NULL)
			root = bt;
		cout << x << " left child is";
		cin >> x;
		if (x != 0){
			cout << "进入" << bt->data << "这个节点的左子树建设" << endl;
			 Build(x, bt->lchild);
		}
		else{
			cout << bt->data << "左子树为空,即将返回上层" << endl;
			bt->lchild = NULL;		
		}	
		cout << bt->data<< " right child is";
		cin >> x;
		if (x != 0){
			cout << "进入" << bt->data << "这个节点的右子树建设" << endl;
			Build(x, bt->rchild);
		}
		else{
			cout << bt->data << "右子树为空,即将返回上层" << endl;
			bt->rchild = NULL;
		}

		return ;
}



  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值