二元查找树的后序遍历结果

题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false

例如输入576911108,由于这一整数序列是如下树的后序遍历结果:

         8
       /  \
      6    10
    / \    / \
   5   7    11

因此返回true

如果输入7465,没有哪棵树的后序遍历的结果是这个序列,因此返回false

分析:这是一道trilogy的笔试题,主要考查对二元查找树的理解。

在后续遍历得到的序列中,最后一个元素为树的根结点。从头开始扫描这个序列,比根结点小的元素都应该位于序列的左半部分;从第一个大于跟结点开始到跟结点前面的一个元素为止,所有元素都应该大于跟结点,因为这部分元素对应的是树的右子树。根据这样的划分,把序列划分为左右两部分,我们递归地确认序列的左、右两部分是不是都是二元查找树。

参考代码:

 

 1 using namespace std;
 2 
 3 ///////////////////////////////////////////////////////////////////////
 4 // Verify whether a squence of integers are the post order traversal
 5 // of a binary search tree (BST)
 6 // Input: squence - the squence of integers
 7 //        length  - the length of squence
 8 // Return: return ture if the squence is traversal result of a BST,
 9 //         otherwise, return false
10 ///////////////////////////////////////////////////////////////////////
11 bool verifySquenceOfBST(int squence[], int length)
12 {
13       if(squence == NULL || length <= 0)
14             return false;
15 
16       // root of a BST is at the end of post order traversal squence
17       int root = squence[length - 1];
18 
19       // the nodes in left sub-tree are less than the root
20       int i = 0;
21       for(; i < length - 1; ++ i)
22       {
23             if(squence[i] > root)
24                   break;
25       }
26 
27       // the nodes in the right sub-tree are greater than the root
28       int j = i;
29       for(; j < length - 1; ++ j)
30       {
31             if(squence[j] < root)
32                   return false;
33       }
34 
35       // verify whether the left sub-tree is a BST
36       bool left = true;
37       if(i > 0)
38             left = verifySquenceOfBST(squence, i);
39 
40       // verify whether the right sub-tree is a BST
41       bool right = true;
42       if(i < length - 1)
43             right = verifySquenceOfBST(squence + i, length - i - 1);
44 
45       return (left && right);
46 }

 

以上转自何海涛博客

 

 

posted @ 2012-07-08 22:42  wolenski  阅读(256)  评论(0编辑  收藏  举报