GeeksforGeeks的文章:
http://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/
题目大意:
给你一个整形数组
题目分析:
题目只需要你判断可能性。因此,我们需要弄明白BST先序遍历的特点。有几点内容:
- 优先沿左子树往下遍历,元素值逐渐变小
- 当左子树不存在时,跳转到同一层最近的右子树,并进行继续优先遍历左子树。
因此,如果数组
问题的关键:性质1有一个前提条件——不断减小的元素存在下界——跳转的根结点。一旦超过下界,那么就违反了BST的性质。例如:
元素9就是元素6的右孩子,那么6就是9这颗子树沿左子树往下遍历的下界。该例中元素8,7都大于6,所以满足性质1的前提条件。如果改变
bool canRepresentBST(int pre[], int n)
{
// Create an empty stack
stack<int> s;
// Initialize current root as minimum possible
// value
int root = INT_MIN;
// Traverse given array
for (int i=0; i<n; i++)
{
// If we find a node who is on right side
// and smaller than root, return false
if (pre[i] < root)
return false;
// If pre[i] is in right subtree of stack top,
// Keep removing items smaller than pre[i]
// and make the last removed item as new
// root.
while (!s.empty() && s.top()<pre[i])
{
root = s.top();
s.pop();
}
// At this point either stack is empty or
// pre[i] is smaller than root, push pre[i]
s.push(pre[i]);
}
return true;
}