#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, -1, sizeof (cache));
bool ret = verify (a, 0, length - 1);
if (ret)
...{
print (a, 0, length - 1);
}
return ret;
}


void main ()
...{
int a[] = ...{2, 4, 7, 9, 8, 5};
bool ret = verifySequence (a, sizeof (a)/sizeof (a[0]));
printf ("%d", ret);
} 
本文介绍了一种验证给定数组是否为二叉排序树后序遍历的方法。通过递归和缓存优化,实现了一个高效算法,并提供了一个完整的C语言实现示例。

被折叠的 条评论
为什么被折叠?



