数据结构 二叉树的建立和遍历(c++堆栈版)

本文详细介绍了如何使用递归方法在C++中创建二叉树,并实现了前序、中序和后序遍历。重点讲解了创建二叉树过程中节点的动态内存分配及递归函数的正确返回方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
using namespace std;
struct BiNode
{
	char data;
	struct BiNode *lchild, *rchild;
};
BiNode* create(BiNode *bt)//创建二叉树
{
		char x;
		cin >> x;
		if (x == '#')
		{
			bt = NULL;
		}
		else
		{
	        bt = new BiNode;//???每次都要分配新的内存空间
			bt->data = x;
			bt->lchild=create(bt->lchild);
			bt->rchild=create(bt->rchild);
		}
		return bt;
}

class Bitree
{
private:
	BiNode *root;
public:
	Bitree();
	void Pre(BiNode *bt);
	void In(BiNode *bt);
	void Post(BiNode *bt);
};
Bitree::Bitree()
{
	root=create(root);
	Pre(root);
	In(root);
	Post(root);
}
void Bitree::Pre(BiNode *bt)
{
	if (bt == NULL) return;
	else
	{
		cout << bt->data;
		Pre(bt->lchild);
		Pre(bt->rchild);
	}
}
void Bitree::In(BiNode *bt)
{
	if (bt == NULL) return;
	else
	{

		Pre(bt->lchild);
		cout << bt->data;
		Pre(bt->rchild);
	}
}
void Bitree::Post(BiNode *bt)
{
	if (bt == NULL) return;
	else
	{

		Pre(bt->lchild);
		Pre(bt->rchild);
		cout << bt->data;
	}
}
int main()
{
	Bitree MyBitree;
	return 0;
}
  • create
    运用递归创建
    每次都返回bt
//最终版
BiNode* create(BiNode *bt)//创建二叉树
{
		char x;
		cin >> x;
		if (x == '#')
		{
			bt = NULL;
		}
		else
		{
	        bt = new BiNode;//???每次都要分配新的内存空间
			bt->data = x;
			bt->lchild=create(bt->lchild);
			bt->rchild=create(bt->rchild);
		}
		return bt;
}

//当没有返回值的时候 根节点一直没有被改变 不能成功创建
void create(BiNode *bt)//创建二叉树
{
		char x;
		cin >> x;//create异常
		if (x == '#')
		{
			bt = NULL; 		}
		else
		{
	        bt = new BiNode;
			bt->data = x;
			create(bt->lchild);
			create(bt->rchild);
		}
}

Tips:
1.注意判断x==‘#’
否则函数不能成功返回
2.
疑问 待整理

      bt = new BiNode;//???每次都要分配新的内存空间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值