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)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.