检测一个数组能否表示二叉搜索树(BST)的先序遍历

来源:互联网 发布:电脑桌面文件分类软件 编辑:程序博客网 时间:2024/06/08 08:59

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;}
0 0
原创粉丝点击