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

判断整数序列是不是二元查找树的后序遍历结果

2012-09-06 15:14 267 查看
二叉树----遍历

一、题目:(感谢 http://blog.csdn.net/v_JULY_v 提供的题目)

判断整数序列是不是二元查找树的后序遍历结果

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

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

     8

    /  \

  6  10

  / \   / \

5 7 9 11

因此返回true。

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

二、分析:
1.整数序列,即序列中可能出现负数

2.后序遍历:左右中

3.(1)以最后一位为基准,把前面的数分为两类,比基准大和比基准小,并且这两类数必须是连续的,否则返回false;

   (2)以此类推,在这两堆数中各找其基准,重复上述操作,如果没有返回false,则返回true。

三、代码:

#include<iostream>
using namespace std;

//正确
const int intArray[] = {-8,-3,-6,12,13,10,19,15,28,32,31,58,38,20};
const int arraySize = 14;

//正确
//const int intArray[] = {5,7,6,9,11,10,8};
//const int arraySize = 7;

//错误
//const int intArray[] = {7,4,6,5};
//const int arraySize = 4;

//错误
//const int intArray[] = {6,12,-13,10,19,15,28,32,31,58,38,20};
//const int arraySize = 12;

bool check(int startPosition,int datumPosition)
{
int leftStart = startPosition;
int leftEnd = 0;
int rightStart = 0;
int rightEnd = datumPosition - 1;

bool isAppear = false;

for(int i=startPosition;i<datumPosition;i++)
{
if(isAppear)
{
if(intArray[i] < intArray[datumPosition]) return false;

}else
{
if(intArray[i] > intArray[datumPosition])
{
leftEnd = i-1;
rightStart = i;

isAppear = true;
}
}
}

if(leftStart<leftEnd) if(!check(leftStart,leftEnd)) return false;
if(rightStart<rightEnd) if(!check(rightStart,rightEnd)) return false;

return true;
}

void main()
{
int datumPosition = arraySize-1;  //基准的位置

if(check(0,datumPosition)) cout<<"true"<<endl;
else cout<<"false"<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐