您的位置:首页 > 其它

判断排序二叉树的后序遍历是否正确(对递归算的总结)

2014-12-09 16:07 381 查看
#include <iostream>
using namespace std;
//排序二叉树的性质
/*
*.终止条件:1.开始>=结尾返回真
*. 		  2.s >= e 因为不出现问题的话,一定能到达 s>=e的情况。知道到达了s >= e即为真
*.
1.最后一个节点是root
2.在root之前的节点 连续的大于root的是其右子树, 再之前连续小于root的是其左子树
3.递归调用
*/
bool treehelper(int a[], int s, int e)
{
if(a == NULL)return 0;
if(s >= e)return 1; 	//在没有右子树的情况下,可能会出现s >= e
int i = e-1;
while( i >= s && a[e] <= a[i] )i--;
if(!treehelper(a,i+1,e-1))
{
return 0;
}
int k = i;
while( i >= s && a[e] > a[i])i--;
if( s < i+1 )return 0;		//如果左子树判断完还有大于root的值,直接说明这不是一颗排序二叉树的后序
return treehelper(a,s, k);
}
int PostorderResult(int a[], int n)
{
return treehelper(a,0,n-1);
}

int main()
{
int a[] = {1,5,7,6,9,11,10,8};
int i = PostorderResult(a,sizeof(a)/sizeof(a[0]));
cout <<	i << std::endl;
return 0;
}
//至于前序的更简单 遍历一下就行了。中序的话
bool treehelper2(int a[], int s, int e)
{
if( a == NULL)return NULL;
if( s >= e)return 1;

int i = s+1;
while( i <= e && a[s] > a[i])i++;
if(!treehelper2(a,s+1,i-1))
{
return 0;
}
int k = i;
while( i <= e && a[s] <= a[i])i++;
if( e > i-1 )return 0;
return treehelper2(a,k,e);
}

这里的递归是很经典的,我自己总结一下,不过总结的不咋点。。。

1.子问题

2.终止条件(包括一些边界)

子问题:每个后序判断都是划分成其左子树的后序一右子树的后序,然后左右子树可以递归下去。这就找到了子问题。

终止条件:当s>=e时,会出现s>=e只有不出问题的递归到每个子节点才有可能发生,当递归到这了,这个后序代表着是没有问题的。

总结的一般形式:

void func(int a, int b)//这里的参数都是控制子问题规模的参数

{

if(...)return ;
//递归的终止条件

//下面是对当前这个问题进行解决,一般都会涉及到子问题

int i = func(a+x,b-x); //这个是对子问题的划分,也是控制子问题

int j = func(a-x,a+x); //

return i*j;
//最后根据子问题返回的值,返回这整个问题的结果。

}

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