您的位置:首页 > 其它

算法习题9:判断整数序列是不是二元查找树的后序遍历结果

2013-10-14 11:43 316 查看
判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
       8
      /   \
    6    10
   / \     / \
  5 7   9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。

------------------------------

后序排列是L R M 先左再右最后中间的输出,所以输出可以分成三块  

左子树块  右子树块  父亲节点

当然左子树块的所有节点必须小于父亲节点, 右子树块的所有节点必须大于父亲节点  如果有出现不同则return false

然后递归  把左子树块分成那三块,比较

参考:http://bbs.csdn.net/topics/350118968

我以另一种笨拙点的方法实现,

我从数组后面开始生成一个二叉树,从后序排列的规律看,如果a(i-1)>a(i) 那么就必须让a(i-1)是a(i)的右亲子节点,否则这就不符和后序输出

其实这个思想也是要求  右子树 必须全部大于父亲节点,如果大于了,但是右子树块里还有小于父亲节点的数,那么是不允许的

程序最后还给出矫正后的输出

//============================================================================
// Name        : JudgeBinaryTree.cpp
// Author      : YLF
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

#define MAX 20

struct Node{
int value;
Node* left;
Node* right;
};

Node* pre = NULL;
Node* head = NULL;

/*
* 这里的判断规则是:如果a(n-1)>a(n)而且a(n-1)还不是a(n)的子节点 那么不是后序遍历
*/
bool addNode(Node* &p, int* arr, int index);
void LRD(Node* p);

int main() {

int arr[MAX];
int input = 0;
int index = -1;
while(true){
index++;
cin>>input;
if(input!=-1)
arr[index] = input;
else break;
}
//开始判断
bool success = true;
while(index>0){
index--;
if(!addNode(head, arr, index)){
success = false;
}
}
if(!success){
cout<<"not!!"<<endl<<"right sort:"<<endl;
LRD(head);
}
else
cout<<"yes!!";
return 0;
}

bool addNode(Node* &p, int* arr, int index){

if(p == NULL){
Node* temp = new Node();
temp->value = arr[index];
temp->left = NULL;
temp->right = NULL;

p = temp;
if((head!=temp) && arr[index]>arr[index+1])
if(pre->right != p)
return false;

pre = p;
return true;
}

if(arr[index] < p->value)
return addNode(p->left, arr, index);
else if(arr[index] >= p->value)
return addNode(p->right, arr, index);
}

void LRD(Node* p){
if(p->left!=NULL)
LRD(p->left);
if(p->right != NULL)
LRD(p->right);
cout<<p->value<<" ";
}


-------------------------output----------------------------
7 4 6 5 -1

not!!

right sort:

4 7 6 5 

--------------------

5 7 6 9 11 10 8 -1

yes!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息