已知二叉排序树的先序求后序

#include<bits/stdc++.h>
using namespace std;
int n,a[105];
typedef struct  BtNode
{
	BtNode *leftchild;
	BtNode *rightchild;
	int val;
}BtNode,*Btree;


Btree newNode(int v){
    BtNode *node = new BtNode;
    node->val = v;
    node->leftchild = NULL;
    node->rightchild = NULL;
    return node;
}

void Bst(BtNode *&root,int a[],int st,int ed){
    if(st > ed) {root = NULL;return ;}
    if(root == NULL){
        root = newNode(a[st]);
    }
    int i = st + 1,temp = root->val;
    while(i <= ed && a[i] < temp) i++;//找到一个大于temp值的位置
    Bst(root->leftchild,a,st + 1,i - 1);
    Bst(root->rightchild,a,i,ed);
}
void postorder(Btree t){
    if(t != NULL){
        postorder(t->leftchild);
        postorder(t->rightchild);
        printf("%d ",t->val);
    }
}


int main(){
   BtNode *root = NULL;
   scanf("%d",&n);
    for(int i = 0; i < n; i++) scanf("%d",&a[i]);
    Bst(root,a,0,n-1);
    postorder(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
已知一棵二叉排序树,我们可以通过计算其平均查找长度(Average Search Length,ASL)来评估其查找效率。二叉排序树的ASL计算公式如下: ASL = (sum_depth + n) / n 其中,sum_depth为所有节点的深度之和,n为节点总数。 下面是一个C语言求已知二叉排序树平均查找长度的代码: ```c #include <stdio.h> #include <stdlib.h> /* 定义二叉树节点结构体 */ typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; /* 插入节点 */ void insert(TreeNode** root, int val) { if (*root == NULL) { *root = (TreeNode*)malloc(sizeof(TreeNode)); (*root)->val = val; (*root)->left = NULL; (*root)->right = NULL; } else if (val < (*root)->val) { insert(&((*root)->left), val); } else { insert(&((*root)->right), val); } } /* 计算二叉排序树的节点总数 */ int countNodes(TreeNode* root) { if (root == NULL) { return 0; } else { return 1 + countNodes(root->left) + countNodes(root->right); } } /* 计算二叉排序树所有节点的深度之和 */ int sumDepth(TreeNode* root, int depth) { if (root == NULL) { return 0; } else { return depth + sumDepth(root->left, depth + 1) + sumDepth(root->right, depth + 1); } } /* 计算二叉排序树的平均查找长度 */ float calculateASL(TreeNode* root) { int n = countNodes(root); int sum_depth = sumDepth(root, 0); float asl = (float)(sum_depth + n) / n; return asl; } int main() { TreeNode* root = NULL; insert(&root, 5); insert(&root, 3); insert(&root, 1); insert(&root, 4); insert(&root, 7); insert(&root, 6); insert(&root, 9); float asl = calculateASL(root); printf("ASL = %.2f\n", asl); return 0; } ``` 在这个代码中,我们先定义了二叉树节点结构体,然后实现了插入节点、计算节点总数、计算所有节点的深度之和和计算平均查找长度的函数。在主函数中,我们创建了一棵二叉排序树,并计算了其平均查找长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值