C++数据结构二叉树实现

#include <iostream>
using namespace std;
//有序二叉树:左子树value小于右子树value


struct node;
typedef struct tree
{
	struct node* p_node;
}; tree;
typedef struct node
{
	int val;
	tree left;
	tree right;
}; node;

typedef void (*pfunc_t)(int);//创建函数指针类型,用于指向函数print_cb
//树的初始化
void tree_init(tree* p_tree)
{
	p_tree->p_node = NULL;//把树设置为没有节点的空树
}
//清除函数
void tree_deinit(tree* p_tree)
{
	if (!p_tree->p_node)
	{
		return;
	}

	tree_deinit(&(p_tree->p_node->left));
	tree_deinit(&(p_tree->p_node->right));
	delete(p_tree->p_node);
	p_tree->p_node = NULL;
}
//查找函数
tree* tree_search(const tree* p_tree,int val)
{
	if (p_tree->p_node== NULL)
	{
		//cout << "第一次节点地址" << endl;
		return (tree *)p_tree;
	}

	if (p_tree->p_node->val == val)
	{
		return (tree *)p_tree;
	}
	else if (p_tree->p_node->val > val)
	{
		return tree_search(&(p_tree->p_node->left), val);
	}
	else
	{
		return tree_search(&(p_tree->p_node->right), val);
	}
}
//插入函数
bool tree_insert(tree* p_tree, int val)
{

	tree* p_tempt = tree_search(p_tree, val);

	//if (p_tempt->p_node==NULL)
	//{
	//	cout << "0" << endl;
	//	return false;
	//}
	node* p_node = new node;
	//p_node = NULL;
	if (!p_node)
	{
		cout << "内存分配失败" << endl;
		return false;
	}
	p_node->val = val;
	p_node->left.p_node = NULL;
	p_node->right.p_node = NULL;
	p_tempt->p_node = p_node;//把动态分布的节点挂在找到的节点上
	//cout << "1" << endl;
	return true;
}
void print_cb(int val)
{
	cout << val << " ";
}
//以中序遍历处理树里所有节点的函数
void tree_miter(const tree *p_tree,pfunc_t p_func)
{
	if (!p_tree->p_node)
	{
		//cout << "0" << endl;
		return;
	}
	tree_miter(&(p_tree->p_node->left), p_func);//递归调用tree_miter函数处理左子树
	p_func(p_tree->p_node->val);
	tree_miter((&p_tree->p_node->right), p_func);
	
}

void test05()
{
	tree tr = { 0 };
	tree_init(&tr);
	tree_insert(&tr, 50);
	tree_insert(&tr, 25);
	tree_insert(&tr, 75);
	tree_insert(&tr, 13);
	tree_insert(&tr, 37);
	tree_insert(&tr, 67);
	tree_insert(&tr, 88);
	tree_insert(&tr, 7);

	tree_miter(&tr, print_cb);
}
int main()
{
	test05();


	system("pause");
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值