Http://zhedahht.blog.163.com/blog/static/25411174200725319627/
Question: enter an integer array to determine whether the array is the result of a binary search tree's sequential traversal. If true is returned, otherwise false is returned.
For example, input 5, 7, 6, 9, 11, 10, and 8, because the integer sequence is the result of post-sequential traversal of the following tree:
8
/\
6 10
/\/\
5 7 9 11
Therefore, true is returned.
If 7, 4, 6, and 5 are input, the result of post-sequential traversal of no tree is this sequence, so false is returned.
Analysis: This is a trilogy pen, mainly to examine the understanding of the Binary Search Tree.
In the subsequent traversal sequence, the last element is the root node of the tree. Scanning this sequence from the beginning, elements smaller than the root node should be located in the left half of the sequence; from the first element greater than the start of the followed node to the end of the followed node, all elements must be greater than the nodes, because these elements correspond to the right subtree of the tree. According to this division, the sequence is divided into the left and right parts. We recursively confirm whether the Left and Right Parts of the sequence are binary search trees.
Reference code:
using namespace std;///////////////////////////////////////////////////////////////////////// Verify whether a squence of integers are the post order traversal// of a binary search tree (BST)// Input: squence - the squence of integers// length - the length of squence// Return: return ture if the squence is traversal result of a BST,// otherwise, return false///////////////////////////////////////////////////////////////////////bool verifySquenceOfBST(int squence[], int length){ if(squence == NULL || length <= 0) return false; // root of a BST is at the end of post order traversal squence int root = squence[length - 1]; // the nodes in left sub-tree are less than the root int i = 0; for(; i < length - 1; ++ i) { if(squence[i] > root) break; } // the nodes in the right sub-tree are greater than the root int j = i; for(; j < length - 1; ++ j) { if(squence[j] < root) return false; } // verify whether the left sub-tree is a BST bool left = true; if(i > 0) left = verifySquenceOfBST(squence, i); // verify whether the right sub-tree is a BST bool right = true; if(i < length - 1) right = verifySquenceOfBST(squence + i, length - i - 1); return (left && right);}