Thought: For the two-fork sort tree , in which the sequence traversal sequence is an ascending ordered sequence , so, for a given two-fork tree in the middle sequence traversal, if the previous value can always be kept smaller than the latter value, then the two fork tree is a binary sort tree. the algorithm is as follows:
KeyType predt=0; //predt is a global variable that holds the pre-order value of the current node, and the initial value is the minimum
int Judgebst (Bstnode *bt)
{
Returns 1 indicates a binary sort tree, and returns 0 that is not
int b1,b2;
if (bt==null)
return 1;
Else
{
B1=judgebst (Bt->lchild); //Judge left subtree
if (b1==0| | Predt>=bt->key)
return 0;
predt=bt->key; //Save the current node's keywords
B2=judgebst (Bt->rchild); //Judging Right sub-tree
return B2;
}
}
Note: if the middle sequence of a binary tree is an ordered sequence, then the two-fork tree must be a binary sort tree.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Design an algorithm to determine whether a given binary tree is a two-fork sort tree (all the keywords of a binary tree are positive integers)