数据结构 | 常见递归实现

本文探讨了使用递归方法在数据结构中实现对半搜索、计算树高、交换子树以及获取二叉搜索树中度为1的节点数量。通过递归算法,可以更高效地解决这些复杂问题。
摘要由CSDN通过智能技术生成

递归实现对半搜索

int recursion_BinSearch(ListSet L, ElemType x, int low, int high){//递归对半搜索
    if(low<=high){
        int mid = (low+high)/2;
        if(x<L.element[mid])
            return recursion_BinSearch(L,x,low,mid-1);
        else if(x>L.element[mid])
            return recursion_BinSearch(L,x,mid+1,high);
        else
            return mid;
    }
    return -1;
}

int recursion_BinSearch(ListSet L, ElemType x){     //递归对半搜索
    int i = recursion_BinSearch(L,x,0,L.n-1);
    return i;
}

递归实现求树高

int Height(BinaryTreeNode *t){		//递归实现求树高
    if(t == NULL){
        return 0;
    }
    if(t->lChild == NULL && t->rChild == NULL){
        return 1;
    }
    return max(Height(t->lChild),Height(t->rChild)) + 1;
}

递归交换子树

void Swap(BinaryTreeNode *t){		//递归交换子树
    if(t == NULL)
        return;
    else{
        BinaryTreeNode *temp = t->lChild;
        t->lChild = t->rChild;
        t->rChild = temp;
        Swap(t->lChild);
        Swap(t->rChild);
    }
}

递归获取度为1的结点的个数

int getOne(BinaryTreeNode *t){      	//递归获取度为1的结点的个数
    if( t == NULL ){	
        return 0;
    }
    if( t->lChild==NULL && t->rChild==NULL ){
        return 1;
    }
    else
        return getOne(t->lChild) + getOne(t->rChild);
}

二叉搜索树插入的递归实现

int BSTreeNodeInsertR(BSTreeNode **tree,DataType x) //搜索树的插入
{
    if(*tree == NULL)
    {
        *tree = BuyTreeNode(x);
        return 0;
    }

    if ((*tree)->_data > x)
        return BSTreeNodeInsertR(&(*tree)->_left,x);
    else if ((*tree)->_data < x)
        return BSTreeNodeInsertR(&(*tree)->_right,x);
    else
        return -1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值