二叉排序树(c++实现)

#include <iostream>
using namespace std;
class btree
{
public:
	btree *left;
	btree *right;
	int data;
    btree(int i):left(NULL),right(NULL),data(i){}
    ~btree();

	void insert(int a);
	static void inorder(const btree*);//中序遍历
	static void rinorder(const btree*);//中序遍历,先遍历右子树

};
void btree::insert(int a)
{
	if (a<data && left)
		left->insert(a);
	else if (a<data && !left)
		left=new btree(a);
	else if (a>data && right)
		right->insert(a);
	else if (a>data && !right)
		right=new btree(a);
}

void btree::inorder(const btree* b)
{
   if (b != NULL)
   {
   	  inorder(b->left);
   	  cout<<b->data<<" ";
   	  inorder(b->right);
   }
}

void btree::rinorder(const btree* b)
{
   if (b != NULL)
   {
   	  rinorder(b->right);
   	  cout<<b->data<<" ";
   	  rinorder(b->left);
   }
}
btree::~btree()
{
	if (left)
		delete left;
	if (right)
		delete right;
}

void main()
{
   int zu[]={45,1,9,12,8,4821,4,5,1651,51};
   btree *root=new btree(zu[0]);

   for (int i = 1; i < 10; ++i)
   {
   	 root->insert(zu[i]);
   }

   btree::inorder(root);
   cout<<endl;
   btree::rinorder(root);
   cout<<endl;
   delete root;
}

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
二叉链表是一种常用的数据结构,可以用来实现二叉排序树二叉排序树是一种特殊的二叉树,它满足以下两个条件: 1. 左子树上所有节点的值都小于根节点的值; 2. 右子树上所有节点的值都大于根节点的值。 在C++中,我们可以通过定义一个二叉树结构体来实现二叉排序树。具体实现步骤如下: 1. 定义二叉树结构体: ``` struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; ``` 2. 实现插入操作: ``` void insert(TreeNode*& root, int val) { if (!root) { root = new TreeNode(val); return; } if (val < root->val) { insert(root->left, val); } else if (val > root->val) { insert(root->right, val); } } ``` 3. 实现查找操作: ``` bool search(TreeNode* root, int val) { if (!root) { return false; } if (root->val == val) { return true; } else if (val < root->val) { return search(root->left, val); } else { return search(root->right, val); } } ``` 4. 实现删除操作: ``` void remove(TreeNode*& root, int val) { if (!root) { return; } if (root->val == val) { if (!root->left && !root->right) { delete root; root = NULL; } else if (!root->left) { TreeNode* temp = root; root = root->right; delete temp; } else if (!root->right) { TreeNode* temp = root; root = root->left; delete temp; } else { TreeNode* temp = root->right; while (temp->left) { temp = temp->left; } root->val = temp->val; remove(root->right, temp->val); } } else if (val < root->val) { remove(root->left, val); } else { remove(root->right, val); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

紫云的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值