檢測一個數組能否表示二叉搜索樹(BST)的先序遍歷

GeeksforGeeks的文章:
http://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/

題目大意:

給你一個整形數組A ,大小爲N 。你需要判斷數組A 是否可能是一個二叉搜索樹的先序遍歷結果。

題目分析:

題目只需要你判斷可能性。因此,我們需要弄明白BST先序遍歷的特點。有幾點內容:

  1. 優先沿左子樹往下遍歷,元素值逐漸變小
  2. 當左子樹不存在時,跳轉到同一層最近的右子樹,並進行繼續優先遍歷左子樹。

因此,如果數組A 在連續減小,說明正在遍歷左子樹,滿足性質1。當出現元素變大的情況時,說明當前元素在右子樹上(性質2),然後依次循環性質1和2.
問題的關鍵:性質1有一個前提條件——不斷減小的元素存在下界——跳轉的根結點。一旦超過下界,那麼就違反了BST的性質。例如:

A=[10,6,5,9,8,7]

元素9就是元素6的右孩子,那麼6就是9這顆子樹沿左子樹往下遍歷的下界。該例中元素8,7都大於6,所以滿足性質1的前提條件。如果改變A=[10,6,5,9,8,7,5] 。那麼5的存在就超過下界,那麼BST不成立。
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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章