数据结构:二叉搜索树

#孩子表示法定义二叉搜索树

struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
}

#结点创建

struct TreeNode* creatNode(int val){
struct TreeNode* node=(struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val=val;
node->left=null;
node->right=null;
return node;
}

#二叉搜索树的查找

bool BSFFind(struct TreeNode *root,int val){
if(root==null){
return false;
}
if(root->val==val){
return true;
}
if(root->val>val){
return BBFFind(root->right,val);
}else{
return BBFFind(root->left,val);
}
}

#二叉搜索树的插入

struct TreeNode *BSTInsert(struct TreeNode *root,int val){
if(root==null){
return creatNode(val);
}
if(val==root->val){
return root;
}
if(val<root->val){
return BSTInsert(root->left,val);
}else{
return BSTInsert(root->right,val);
}
return root;
}

#查找最小节点

int BSTFindMin(struct TreeNode *root){
if(root->left){
return BFSFindMin(root->left);
}
return root->val;
}

#删除给定节点

struct TreeNode *BSTDelete(struct TreeNode *root,int val){
if(root==null){
return null;
if(val==root->val){
return delete(root);
}
if(val<root->val){
return BSTDelete(root->left,val);
}else{
return BSTDelete(root->right,val);
}
return root;
}

#删除给定二叉搜索树的新节点

struct TreeNode *Delete(struct TreeNode* root)
{
struct TreeNode *delnode,*retnode;
if(root->left==null){
delnode=root,retnode=root->right,free(delnode);
}else if(root->right==null){
delnode=root,retnode=root->left,free(delnode);
}else{
retnode=(struct TreeNode)malloc(sizeof(struct TreeNode));
retnode->val=BSTFindMin(root->right);
retnode->right=BSTDelete(root->right,retnode->val);
retnode->left=noot->left;
}
return retnode;
}

#二叉搜索树的构造

struct TreeNode *BSTConstrct(int *val,int valsize){
int i;
struct TreeNode *root=null;
for(i=0;i<valsize;i++){
BSTInsert(root,val[i]);
}
return root;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值