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;
}