Verify preorder Sequence in Binary Search Tree
\given An array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
Assume each of the sequence is unique.
Follow Up:could does it using only constant space complexity?
Analysis: http://my.oschina.net/u/922297/blog/498356
First, to review the BST, given a node, all the nodes of the left subtree are smaller than that node, and all nodes of the right subtree are larger than that node; the preorder sequence refers to the time when the BST is traversed, the root node is recorded, the left subtree is traversed, and then the right subtree is traversed. So a preorder sequence has such a characteristic that the sequence of the Zuozi must precede the sequence of the right subtree, and the sequence of the left subtree must be small, and the sequence of the right subtree is greater than the root node;
According to the above features it is easy to do it recursively:
If the sequence has only one or two elements, then it must be correct;
If more than two elements, with the current node as the root node, and from the current node to traverse backward until the node is greater than the root node (or to the tail), then the root node, after the node is greater than the root node, is Zuozi, the node is greater than the root node and then the right sub-tree;
So when does a sequence definitely not be a preorder sequence? The right subtree in front of you, if there is a number smaller than the root node, then you can return false directly.
PublicBoolean Verifypreorder (int[] seq,intStartintend) { if(Start +1>=end)return true; intRoot =Seq[start]; inti = start +1; while(I <= end && Seq[i] <root) {i++; } if(I <end) { intj =i; while(J <= End && Seq[j] >root) {J++; } if(J <end) { return false; } returnVerifypreorder (seq, start +1I1) &&Verifypreorder (seq, I, end); } Else { returnVerifypreorder (seq, start +1, end); } }
Verify inorder Sequence in Binary Search Tree
Determines whether the array is incremented.
Verify postorder Sequence in Binary Search Tree
Judge Postorder and above to judge preorder is exactly the same, the last one is root, and then sweep, if the current value is greater than root, then determine whether the left and right part is BST, and judge that all the values on the right are greater than root.
1 PublicBoolean Verifypostorder (int[] preorder) {2 returnVerifypostorder (Preorder,0, Preorder.length-1);3 }4 5 PublicBoolean Verifypostorder (int[] seq,intStartintend) {6 if(Start +1>=end)7 return true;8 9 intRoot =Seq[end];Ten inti =start; One while(I <= End-1&& Seq[i] <root) { Ai++; - } - if(I < end-1) { the intj =i; - while(J <= End-1&& Seq[j] >root) { -J + +; - } + if(J < End-1) { - return false; + } A at returnVerifypostorder (seq, start, I-1) && Verifypostorder (seq, I, End-1); -}Else { - returnVerifypostorder (seq, start, End-1); - } -}
Verify preorder/inorder/postorder Sequence in Binary Search Tree