BST二叉排序树

 1递归构造二叉排序树

#include "binary_sort_tree.h"

BiTreeNode* insertBiSortTree(BiTreeNode *root, int key){
    if (root == NULL) {//递归出口 插入
        root = (BiTreeNode*)malloc(sizeof(BiTreeNode));
        //BiTreeNode *parent = root;
        root->data = key;
        root->left = NULL;
        root->right = NULL;
    }
    else if (key < root->data) {
        BiTreeNode* parent = root;
        parent->left = insertBiSortTree(root->left, key);
        root = parent;
    }
    else if (key > root->data) {
        BiTreeNode* parent = root;
        parent->right = insertBiSortTree(root->right, key);
        root = parent;
    }
    return root;
}

BiTreeNode* creatBiSortTree(int* arr, int n)
// 功能:实现创建升序二叉排序树
// 输入:无序整数数列arr,数列个数n
// 返回:升序二叉排序树根节点
{
    // 请在这里补充代码,完成本关任务
    /********** Begin *********/
    BiTreeNode* BT=NULL;
    for (int i = 0; i < n; i++) {
        BT = insertBiSortTree(BT, arr[i]);//需要每次都传入根节点 就需要每次返回根结点
    }//遍历数组构造树 插入函数有返回值 必须递归
    return BT;
    /********** End **********/
}

2中序遍历二叉排序树

#include "binary_sort_tree.h"
int* InOrder(BiTreeNode* root, int* arr, int& i)
// 功能:实现升序二叉排序树的中序遍历
// 参数:二叉树根节点root,整数数列arr,起始下标i=0
// 返回:中序遍历数列arr  中序遍历放入数组中
{//非递归中序遍历
    BiTreeNode* stack[60];
    int stackTop = -1;
    BiTreeNode* pMove = root;
    while (stackTop != -1 || pMove != NULL) {
        while (pMove) {
            stack[++stackTop] = pMove;
            pMove = pMove->left;//深度 直到左子树遍历完
        }//无路可走 出栈
        if (stackTop != -1) {
            pMove = stack[stackTop--];//取栈顶
            arr[i++]=pMove->data;
            pMove = pMove->right;
        }
    }
    return arr;
}

bool isOrder(int* arr, int n)
// 功能:判断数列arr是否升序
// 参数:数列arr,数列个数n
// 返回:若升序返回true,否则返回false
{
    // 请在这里补充代码,完成本关任务
    /********** Begin *********/
    for (int i = 0; i + 1 < n; i++) {
        if (!(arr[i] < arr[i + 1]))return false;
    }return true;
    /********** End **********/
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值