//Test.cpp:Defines the entry point for the console application.//#include"stdafx.h"#include<iostream>using namespaceStd;typedefstructbtree{CharVal; structBTree *lchild,*Rchild;} BTree;//establishing two-pronged tree in the first orderBTree * Createbtree (BTree *T) {Charvalue; CIN>>value; if('#'==value) T=NULL; Else{T=NewBTree; T->val =value; cout<<" left of"<<T->val<<" :"<<Endl; T->lchild=createbtree (t->lchild); cout<<" right of"<<T->val<<" :"<<Endl; T->rchild=createbtree (t->rchild); } returnT;}
/ * Create a two-fork sorting tree * / BTree* Insertnode (BTree *root,intvalue) {BTree* p=NewBTree (); P->val=value; P->lchild=NULL; P->rchild=NULL; if(root==NULL) {Root=p; returnRoot; } if(value<=root->val) Root->lchild=insertnode (root->lchild,value); Else if(value>root->val) Root->rchild=insertnode (root->rchild,value); returnRoot; }//first-order traversal of binary treevoidPreordertraverse (btree*T) { if(T) {printf ("%c",t->val); Preordertraverse (T-lchild); Preordertraverse (T-rchild); }}//Middle Sequence TraversalvoidInordertraverse (btree*T) { if(t) {Inordertraverse (t-lchild); printf ("%c",t->val); Inordertraverse (T-rchild); }}//Post-post traversalvoidPostordertraverse (btree*T) { if(t) {Postordertraverse (t-lchild); Postordertraverse (T-rchild); printf ("%c",t->val); }}
// recursive traversal of binary tree Whether it is a two-fork sort tree intIssearchtree (BTree *t){ 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->val>t->val)return 0; Else returnIssearchtree (t->lchild); } Else if((t->rchild) &&! (T->lchild))//only right subtree situation { if(t->rchild->val<t->val)return 0; Else returnIssearchtree (t->rchild); } Else //The left and right sub-trees are full . { if((t->lchild->val>t->val) | | (t->rchild->val<t->val)) return 0; Else return(Issearchtree (T->lchild) && Issearchtree (t->rchild)); }}/* complex syntax, but less code to determine the binary sorting tree method * /intprev=int_min;intJudgebst (BTree *t) { intb1,b2; if(t==NULL)return 1; Else{B1=judgebst (t->lchild); if(b1==0|| Prev>=t->val)return 0; Prev=t->Val; B2=judgebst (t->rchild); returnB2; }}intMainintargcChar*argv[]) { /*Establish*/BTree*root=NewBTree (); printf ("creating a binary tree with root:\n"); Root=Createbtree (root); /*Output*/Preordertraverse (root); printf ("\ n"); Inordertraverse (root); printf ("\ n"); Postordertraverse (root); printf ("\ n"); /*whether to sort the tree*/printf ("%d\n", Issearchtree (root)); printf ("%d\n", Judgebst (root)); System ("Pause"); return 0;}
A binary sort tree is a two-prong tree in which the middle sequence traverses the result as an increment, such as:
Binary tree establishment, traversal and two-fork sorting tree judgment "C + +"