Binary search tree: Two forks the left side of the root node is smaller than the root node, and the right side is larger than the root node.
Example: Enter an array to determine if the sequential traversal sequence for a two-fork search tree, if yes, returns True, if not, returns flase, assuming there are no duplicate elements.
Idea: Because it is a sequential traversal, so the last node of the array is the root node, and, because it is a two fork tree, so the data is divided into two parts, the right part is smaller than the root node, the left is larger than the root node. The left and right sides are also two-fork tree, so it can be implemented by recursion.
Java code:
Public classIsbinarysearchtree { Public BooleanIsbst (int[] sequence,intStartintLen) { if(sequence==NULL|| Len<=0) return false; intRoot=sequence[len-1]; //Two forks the left side of the search tree is smaller than the root node, and the right side is larger. intI=0; while(i<len-1){ if(sequence[i]>root) Break; I++; } intj=i; while(j<len-1){ if(sequence[j]<root)return false; J++; } //determine if the left subtree is a binary search tree Booleanleft=true; if(i>0) Left=isbst (sequence,0, i); //Judging right subtree is not binary search tree Booleanright=true; if(i<len-1) Right=isbst (sequence,i,len-i-1); returnleft&&Right ; } Public Static voidMain (string[] args) {int[] a={3,5,6}; Isbinarysearchtree IBT=NewIsbinarysearchtree (); if(Ibt.isbst (A, 0, A.length)) {System.out.println ("Is Binarysearchtree endroot"); } ElseSystem.out.println ("is not binarysearchtree endroot"); }}
offer-the fourth chapter of the sword to solve the problem of the idea (determine whether an array is a two-fork search tree sequential traversal sequence)