noj25二叉排序树的插入和删除

本文介绍了一种二叉排序树的实现方法,包括初始化、插入、中序遍历及删除等基本操作,并通过示例代码展示了如何进行特定区间的元素输出。

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

在这里插入图片描述
在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>
//二叉排序树
typedef struct BiNode
{
    int data;
    struct BiNode *leftchild,*rightchild;
}BiNode,*BiNodePtr,*BiTree;
//初始化二叉排序树
BiNodePtr InitTree(BiTree T)
{
    int e;
    scanf("%d",&e);
    if(e!=-1)
    {
        T=(BiNodePtr)malloc(sizeof(BiNode));
        T->data=e;
        T->leftchild=InitTree(T->leftchild);
        T->rightchild=InitTree(T->rightchild);
    }
    else
    {
        T=NULL;
    }
    return T;
}

//二叉排序树插入
BiTree insertBST(BiTree bt,int val)//bt应该为引用,因为层层改变
{
    if(bt==NULL)
    {
        BiNodePtr S;
        S=(BiNodePtr)malloc(sizeof(BiNode));
        S->data=val;
        S->leftchild=NULL;
        S->rightchild=NULL;
        bt=S;
    }
    else
    {
        if(val<bt->data) bt->leftchild=insertBST(bt->leftchild,val);
        else bt->rightchild=insertBST(bt->rightchild,val);
    }
    return bt;
}

//二叉树的中序遍历
void InOrderTraverse(BiTree T)
{
   if(T==NULL)
       return ;
   InOrderTraverse(T->leftchild);
   printf("%d ",T->data);
   InOrderTraverse(T->rightchild);
}
//输出特定区间
void PrintBTs(BiTree T,int min,int max)
{
   if(T==NULL)
       return ;
  
   PrintBTs(T->leftchild,min,max);
   if(T->data>min && T->data<max)printf("%d ",T->data);
   PrintBTs(T->rightchild,min,max);

}

//删除二叉树
void DeleteBTS(BiTree T,int val)
{
    if(T==NULL)
       return ;
   
    BiTree f,p;
    p=T;
    f=NULL;
    while(p)
    {
        if(p->data==val)//找到跳出
        break;
        else
        {
            f=p;//f为p的双亲
            if(p->data>val) p=p->leftchild;//去左子树找小的
            else p=p->rightchild;//去右子树找大的
        }
    }
    BiNodePtr q,s;
    //第一种情况,被删除的结点左右子树都存在,可以去左子树找最大,也可以去右子树找最小
    if((p->leftchild)&&(p->rightchild))//都不空
    {
        q=p;
        s=p->leftchild;
        while(s->rightchild)
            {
                q=s;
                s=s->rightchild;
            }
        p->data = s->data;
        if(q!=p)//重新连接q的左子树
        {
            q->rightchild=s->leftchild;
        }
        else
        {
            q->leftchild=s->leftchild;
        }
        free(s);
        return;
    }
    //p的右子树空,或都空
    else if(p->rightchild==NULL)
    {
        if(f)//判断被删结点是否为根结点,若是,则f=null;
        {
            if(f->leftchild==p)//被删结点的双亲结点的左孩子为p
            {
                f->leftchild=p->leftchild;
                p->leftchild=NULL;
            }
            else//被删结点的双亲结点的右孩子为p
            {
                f->rightchild=p->leftchild;
                p->leftchild=NULL;
            }
            free(p);
            return;
        }
        else//被删结点为根节点
        {
            f=p;
            p=p->leftchild;
            f->leftchild=NULL;
            free(f);
            T=p;
            return;
        }
    }
    //p的左子树空,或者都空
    else
    {
        if(f)//不是根节点
        {
            if(f->leftchild==p)//被删的p为左孩子
            {
                f->leftchild=p->rightchild;
                p->rightchild=NULL;
            }
            else//被删的p为有孩子
            {
                f->rightchild=p->rightchild;
                p->rightchild=NULL;
            }
            free(p);
        }
        else//被删的p为根节点
        {
            f=p;
            p=p->rightchild;
            f->leftchild=NULL;
            free(f);
            T=p;
            return;
        }
    }
}
int main()
{
    BiTree T;
    T=InitTree(T);

    int min,max;
    scanf("%d %d",&min,&max);

    int insert;
    scanf("%d",&insert);
    int del;
    scanf("%d",&del);

    PrintBTs(T,min,max);
    printf("\n");

    insertBST(T,insert);
    InOrderTraverse(T);
    DeleteBTS(T,insert);
    printf("\n");

    DeleteBTS(T,del);
    InOrderTraverse(T);
    printf("\n");
    return 0;
}
### NOJ 中与树相关的题目及解法 #### 树的概念及其重要性 树是一种重要的数据结构,在计算机科学中有广泛的应用。它由节点边组成,具有层次化的特性。常见的树有二叉树、平衡二叉树(AVL)、红黑树以及堆等变体[^1]。 #### 常见的树操作 对于树的操作通常包括但不限于以下几个方面: - **构建树**:通过输入的数据建立一棵树。 - **遍历树**:前序、中序、后序以及层序遍历是基本的四种方式[^2]。 - **查找节点**:在给定条件下寻找特定节点。 - **更新或删除节点**:修改或者移除某些节点并保持树的整体性质不变。 下面是一些可能涉及这些操作的具体例子: --- #### 题目一:二叉搜索树 (Binary Search Tree) 的构造与查询 ##### 描述 给出一组整数序列,按照顺序依次插入到初始为空的一棵二叉搜索树中,并完成如下任务: 1. 构建该二叉搜索树; 2. 查询某个值是否存在; 3. 输出按某种次序遍历的结果。 ##### 解决方案 可以采用递归方法实现二叉搜索树的插入功能。以下是 Python 实现的一个简单版本: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def insert_into_bst(root, val): if not root: return TreeNode(val) if val < root.val: root.left = insert_into_bst(root.left, val) elif val > root.val: root.right = insert_into_bst(root.right, val) return root def inorder_traversal(root): result = [] stack = [(root, False)] while stack: node, visited = stack.pop() if node: if visited: result.append(node.val) else: stack.append((node.right, False)) stack.append((node, True)) stack.append((node.left, False)) return result ``` 上述代码实现了二叉搜索树的插入函数 `insert_into_bst` 基于栈的中序遍历算法 `inorder_traversal`[^3]。 --- #### 题目二:最小生成树 (Minimum Spanning Tree) ##### 描述 在一个无向加权图中,求连接所有顶点且总权重最小的子集边集合。 ##### 解决方案 常用的两种算法分别是 Kruscal 算法 Prim 算法。这里展示 Kruscal 算法的一种 C++ 实现: ```cpp #include <bits/stdc++.h> using namespace std; struct Edge { int u, v, w; }; bool cmp(const Edge &a, const Edge &b) { return a.w < b.w; } int find_set(int parent[], int x) { if(parent[x] != x){ parent[x] = find_set(parent,parent[x]); } return parent[x]; } void union_set(int parent[], int rank[], int x, int y) { int fx = find_set(parent,x); int fy = find_set(parent,y); if(fx == fy) return ; if(rank[fx]>rank[fy]){ parent[fy] = fx; }else{ parent[fx] = fy; if(rank[fx]==rank[fy]) rank[fy]++; } } int kruskal(vector<Edge> edges,int n){ sort(edges.begin(),edges.end(),cmp); int res = 0,cnt = 0; int parent[n],rank_arr[n]; for(int i=0;i<n;i++){ parent[i] = i; rank_arr[i] = 0; } for(auto e : edges){ if(find_set(parent,e.u)!=find_set(parent,e.v)){ cnt++; res +=e.w; union_set(parent,rank_arr,e.u,e.v); if(cnt==n-1) break ; } } return res; } ``` 此程序利用了并查集的思想来解决连通性环检测问题[^4]。 --- #### 题目三:最近公共祖先 (Lowest Common Ancestor) ##### 描述 在一棵树上找到两个指定结点之间的最低共同祖先。 ##### 解决方案 可以通过深度优先搜索的方式自底向上回溯得到 LCA 结果。下面是伪代码描述过程的一部分逻辑框架: ```pseudo function lca(node, p, q): if node is null or node equals either p or q then return node let left be the recursive call to this function on the left child of 'node' let right be the same but with respect to its right subtree instead if both are non-null it means one lies in each branch so our current position must indeed represent their lowest common ancestor hence we should output that fact immediately otherwise propagate whichever answer was found upwards accordingly. ``` 实际编码时需注意边界条件处理以及性能调优等问题[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值