The topic description of sequential traversal sequence of binary search tree
Enter an array of integers to determine if the array is the result of a sequential traversal of a binary search tree. If yes, output yes, otherwise output No. Assume that any two digits of the input array are different.
Ideas
- Post-loop traversal: left-to-right--root node
- Binary search tree, Zuozi node Small root node, right subtree node is greater than the root node
- Recursive invocation, according to the size of the difference between the left and right subtree, if the node is found in the tree of the small root node, it is not the subsequent traversal sequence
- Extrapolate: If it is required to process a binary tree traversal sequence, we can first find the root node of the two fork tree, and then split the whole tree's traversal sequence into the corresponding sub-sequence of the left subtree and the right subtree, and then recursively process the two sub-sequences.
Code
PublicClass Solution {public Boolean Verifysquenceofbst (int []Sequence) {if (sequence = = NULL | |Sequence.length = =0) {return false; }ReturnVerifySequence0,Sequence.length-1); }public BooleanVerifyInt[]Dataint start,IntEnd) {if (data = = NULL | |Data.length = =0) {return false;} The node of the left subtree in the binary search tree is small root node.int i = start;for (; i <End i++) {if (Data[i] >data[end]) {break;}} The node of the right subtree in the binary search tree is greater than the root node int j = i;for (; j < end; j + +) {if (data[j] < data[ end]) {return false;}}//Determine if the left subtree is not a binary search tree, Boolean, or true; if (I-start > 0) {left = verify ( data, start, I-1);} Determine if the right subtree is a binary search tree. if (i < end) {right = verify ( Span class= "Hljs-type" >data, I, end-1);} return (left && right);}
Two fork search tree sequential traversal sequence-Sword point offer