From Leetcode https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/
For example, sequence 2, 1, 3 is the preorder sequence of BST as:
But 2, 3, 1 will not be a preorder sequence;
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 element, then it must be correct, corresponding to a tree with only one node;
If more than one element, the current node is the root node, and from the current node to traverse backwards, until the node is greater than the root node (or to the tail), then the root node, before the large node is Zuozi, the large sections point and then the composition of the right sub-tree;
So when does a sequence definitely not be a preorder sequence? The right sub-tree in front of it, if there is more than the root node is smaller than the number, then you can directly return false;
The code is as follows:
Public boolean verifypreorder (Int[] preorder) { return Verifypreorder (preorder, 0, preorder.length);} Public boolean verifypreorder (int[] seq, int start, int end) { if (start + 1 >= end) { return true; } int root = seq[ start]; int i = start + 1; while ( I < end && seq[i] < root) { i++; } if (i < end) { int j = i; while (j < end && seq[j] > root) { j++; } if (j < end) { return false; } return Verifypreorder (seq, start + 1, i) && verifypreorder (seq, i, End); } else { return Verifypreorder (seq, start + 1, end); }}
Verifies whether a given sequence is a preoder sequence of BST