您的位置:首页 > 职场人生

微软面试之9题 判断整数序列是不是二元查找树的后续遍历结果

2012-11-19 09:10 483 查看
http://blog.csdn.net/v_JULY_v/article/details/6126406

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

如果是返回true,否则返回false。

例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:

    8

   / /

  6  10

/ / / /

5 7 9 11

因此返回true。

如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。

//貌似,少有人关注此题。:).2010/10/18

bool verifySquenceOfBST(int squence[], int length)

{

      if(squence == NULL || length <= 0)

            return false;
      // root of a BST is at the end of post order traversal squence

      int root = squence[length - 1];
      // the nodes in left sub-tree are less than the root

      int i = 0;

      for(; i < length - 1; ++ i)

      {

            if(squence[i] > root)

                  break;

      }
      // the nodes in the right sub-tree are greater than the root

      int j = i;

      for(; j < length - 1; ++ j)

      {

            if(squence[j] < root)

                  return false;

      }
      // verify whether the left sub-tree is a BST

      bool left = true;

      if(i > 0)

            left = verifySquenceOfBST(squence, i);
      // verify whether the right sub-tree is a BST

      bool right = true;

      if(i < length - 1)

            right = verifySquenceOfBST(squence + i, length - i - 1);
      return (left && right);

}

关于第9题:

其实,就是一个后序遍历二叉树的算法。

关键点:

1.

      //确定根结点

      int root = squence[length - 1];
2.

      // the nodes in left sub-tree are less than the root

      int i = 0;

      for(; i < length - 1; ++ i)

      {

            if(squence[i] > root)

                  break;

      }
      // the nodes in the right sub-tree are greater than the root

      int j = i;

      for(; j < length - 1; ++ j)

      {

            if(squence[j] < root)

                  return false;

      }
3.

递归遍历,左右子树。
 
 
bool verifySquenceOfBST(char sequence[],int length)
{
if(sequence==NULL || length<=0)
return false;
int i=0;
cout<<sequence[length-1]<<endl;
for(;i<length-1;i++)
{
if(sequence[i]>sequence[length-1])
{
break;
}
}
int j=i;
for(;j<length-1;j++)
{
if(sequence[j]<sequence[length-1])
{
return false;
}
}
bool left=true;
if(i>0)
{
left=verifySquenceOfBST(sequence,i);
}
bool right=true;
if(i<length-1)
right=verifySquenceOfBST(sequence+i,length-1-i);
return left&right;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐