c++ note--二叉树的实现

二叉树是一种非线性的数据结构。


//定义二叉树

struct Binary_tree
{
	char m_data;		//节点存放的数据
	Binary_tree *m_left;	//左子树节点指针
	Binary_tree *m_right;	//右子树节点指针
};

//二叉树初始化

Binary_tree * My_Init(char data)
{
	Binary_tree * m_node;
	m_node = new Binary_tree;
	m_node->m_data = data;
	m_node->m_left = NULL;
	m_node->m_right = NULL;
	if (m_node != NULL)
		return m_node;
	else
		return NULL;
}
//二叉树查找

Binary_tree * My_find(Binary_tree * treenode,char data)
{
	Binary_tree *ptr;
	if (treenode == NULL)
		return NULL;
	else
	{
		if (data == treenode->m_data)
			return treenode;
		else
		{
			if (ptr = My_find(treenode->m_left, data))
				return ptr;
			else if (ptr = My_find(treenode->m_right, data))
				return ptr;
			else
				return NULL;
		}
	}
}

//二叉树插入节点

void My_insert(Binary_tree *parent_node, char parent_data,string type,char insert_data)
{
	Binary_tree *pnode, *parent;
	pnode = new Binary_tree;
	pnode->m_left = NULL;
	pnode->m_right = NULL;
	pnode->m_data = insert_data;
	parent = My_find(parent_node, parent_data);
	if (!parent)
	{
		delete pnode;
		cout << "the parent tree node is NULL" << endl;
		return;
	}
	if (type == "left")
	{
		cout << "add the node to the left" << endl;
		if (parent->m_left)
			cout << "the left node is not NULL" << endl;
		else
		{
			parent->m_left = pnode;
			cout << "node add ok" << endl;
		}
	}
	else if (type == "right")
	{
		cout << "add the node to the right" << endl;
		if (parent->m_right)
			cout << "the right node is not NULL" << endl;
		else
		{
			parent->m_right = pnode;
			cout << "node add ok" << endl;
		}
	}
	else
		cout << "parameter is error" << endl;
}


//二叉树深度

int My_depth(Binary_tree *treenode)
{
	int depleft, depright;
	if (!treenode)
		return 0;
	else
	{
		depleft = My_depth(treenode->m_left);
		depright = My_depth(treenode->m_right);
		return depleft >= depright ? depleft + 1 : depright + 1;
	}
}

//二叉树前序遍历
void My_show(Binary_tree *treenode)
{
	if (treenode)
	{
		cout << treenode->m_data << endl;
		My_show(treenode->m_left);
		My_show(treenode->m_right);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值