The code for judging the binary sort tree is as follows:
Static Boolean Issearchtree (Bitree *t) {if (!t) //Empty binary tree case return True;else if (! ( T.lchild) &&! (t.rchild)) The left and right subtrees have no situation return True;else if ((t.lchild) &&! ( T.rchild) { //Only left dial hand tree condition if (t.lchild.data>t.data) return False;elsereturn issearchtree (t.lchild);} else if ((T.rchild) &&! ( T.lchild) { //Only right subtree case if (t.rchild.data<t.data) return False;elsereturn issearchtree (t.rchild);} else{ //left and right sub-trees all have the condition if ((t.lchild.data>t.data) | | | (T.rchild.data<t.data)) Return False;elsereturn (Issearchtree (t.lchild) && Issearchtree (T.rchild));}}
The complete source code is as follows:
#include"stdio.h"#include"stdlib.h"typedefstructnode{intdata; structNode *lchild,*Rchild;} Bitree; Bitree*b[ -]; Bitree*Createbitree () {intNum,i,n; Bitree*t,*s; T=NULL; printf ("create a two-fork tree (1 is a virtual node, and 0 means end of input):/n"); Num=0; scanf ("%d",&N); while(n!=0) {s= (Bitree *)malloc(sizeof(Bitree)); S->data=N; S->lchild=s->rchild=NULL; Num++; if(!t) T=s; B[num]=s; scanf ("%d",&N); } for(i=1; i<=num;i++) { if(b[i]->data!=1) { if(2*i<=num && b[2*i]->data!=1) B[i]->lchild=b[2*i]; if(2*i+1<=num && b[2*i+1]->data!=1) B[i]->rchild=b[2*i+1]; } } returnt;}intIssearchtree (ConstBitree *t)//recursive traversal of a binary tree if it is a two-fork sort tree{ if(!t)//Empty binary tree case return 1; Else if(! (t->lchild) &&! (T->rchild))//There are no conditions in the left and right subtrees return 1; Else if((t->lchild) &&! (T->rchild))//only the left dial hand tree situation { if(t->lchild->data>t->data)return 0; Else returnIssearchtree (t->lchild); } Else if((t->rchild) &&! (T->lchild))//only right subtree situation { if(t->rchild->data<t->data)return 0; Else returnIssearchtree (t->rchild); } Else //The left and right sub-trees are full . { if((t->lchild->data>t->data) | | (t->rchild->data<t->data)) return 0; Else return(Issearchtree (T->lchild) && Issearchtree (t->rchild)); }}intMainvoid){ intflag=0; Bitree*Tree; Tree=Createbitree (); Flag=Issearchtree (tree); if(flag) printf ("This tree is a two-fork sorting tree! /n"); Elseprintf ("This tree is not a binary sort tree! /n"); System ("Pause"); return 0;}
Determine if a binary tree is a two-fork sort tree