确定后序遍历二叉树是否构成二叉排序树

本文介绍了一种验证给定数组是否为二叉排序树后序遍历的方法。通过递归和缓存优化,实现了一个高效算法,并提供了一个完整的C语言实现示例。
 
#include <stdio.h>
#include 
<stdlib.h>
#include 
<memory.h>

#define MAX 100

int cache[MAX][MAX][MAX];

int splits[MAX][MAX];

bool ok (int a[], int start, int split, int end);


bool verify (int a[], int start, int end)
{
 
if (start == end || end == start + 1)
 
{
  
return true;
 }


 
for (int split = start; split < end; split++)
 
{
  
if (ok (a, start, split, end))
  
{
   splits[start][end] 
= split;
   
return true;
  }

 }


 
return false;
}


int Max (int a[], int start, int end)
{
 
int max = a[start];

 
for (int i = start + 1; i <= end; i++)
 
{
  
if (max < a[i])
  
{
   max 
= a[i];
  }

 }


 
return max;
}


int Min (int a[], int start, int end)
{
 
int min = a[start];

 
for (int i = start + 1; i <= end; i++)
 
{
  
if (min > a[i])
  
{
   min 
= a[i];
  }

 }


 
return min;
}



bool ok (int a[], int start, int split, int end)
{
 
if (cache[start][split][end] == 1)
 
{
  
return true;
 }


 
if (cache[start][split][end] == 0)
 
{
  
return false;
 }


 
if (start <= split - 1)
 
{
  
if (Max (a, start, split - 1> a[end])
  
{
   cache[start][split][end] 
= 0;
   
return false;
  }

 }


 
if (split + 1 <= end - 1)
 
{
  
if (Min (a, split + 1, end - 1< a[end])
  
{
   cache[start][split][end] 
= 0;
   
return false;
  }

 }


 
if (verify (a, start, split) && verify (a, split + 1, end - 1))
 
{
  cache[start][split][end] 
= 1;
  
return true;
 }


 cache[start][split][end] 
= 0;
 
return false;
}


void print (int a[], int start, int end)
{
 
if (start == end)
 
{
  printf (
"%d ", a[start]);
  
return;
 }


 
if (start < end)
 
{
  
int split = splits[start][end];
  print(a, start, split);
  printf (
"%d ", a[end]);
  print(a, split 
+ 1, end - 1);
  
 }

}


bool verifySequence (int a[], int length)
{
 memset (cache, 
-1sizeof (cache));

 
bool ret = verify (a, 0, length - 1);

 
if (ret)
 
{
  print (a, 
0, length - 1);
 }


 
return ret;
}




void main ()
{
 
int a[] = {247985};
 
bool ret = verifySequence (a, sizeof (a)/sizeof (a[0]));
 printf (
"%d", ret);

}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值