二叉排序树的查找
#include#include /* 递归前中后遍历 */ typedef struct node { int data; struct node*left; struct node*right; }BTnode; BTnode*CreateTree(int a[],int n){ BTnode*root,*c,*p,*pa; int i; root=(BTnode*)malloc(sizeof(BTnode)); root->data=a[0]; root->left=root->right=NULL;//建立根节点 for(i=1;i data=a[i]; p->left=p->right=NULL; c=root; //根节点给C指针 while(c) { //判断p结点时属于左子树还是右子树 pa=c; //pa指针是p结点的父节点 if(c->data>p->data) c=c->left; else c=c->right; } if(pa->data>p->data) //p结点时父节点的左孩子还是右孩子 pa->left=p; else pa->right=p; } return root; } BTnode * Query(BTnode *root,BTnode *parent,BTnode *p,int key) { if(!root) p = parent; return NULL; if(root->data == key) p=root; return root; if(key data ) return Query(root->left,root,p,key); if(key >root->data ) return Query(root->right,root,p,key); } void Forder(BTnode*root) { if(root){ printf("%d",root->data); printf("\n"); Forder(root->left); Forder(root->right); } } void Inorder(BTnode*root) { if(root){ Inorder(root->left); printf("%3d",root->data); printf("\n"); Inorder(root->right); } } void Porder(BTnode*root) { if(root){ Porder(root->left); Porder(root->right); printf("%6d",root->data); printf("\n"); } } int main(void) { BTnode*root; int *a; int n; int i; printf("请输入n="); scanf("%d",&n); a=(int*)malloc(n*sizeof(int)); printf("请输入数组a[]="); for(i=0;i data); }
本文标题:二叉排序树的查找
分享链接:http://cdiso.cn/article/ijhopj.html