JSMS33-输入数组检测是否位某二叉树的后序遍历-剑指offer24

209 阅读1分钟

题目描述:这道题就是让你写一个函数postOrder(int *a,int len,tree *t);传入一个数组(长度任意),判断是否位某二叉树及其子树的后续遍历顺序。

解析:书上是用的递归,我是用非递归后序遍历来解决的,这样比较简单。非递归遍历二叉树就是创建两个栈,栈a做为辅助栈,栈b纪录后序遍历的顺序,然后输出栈b的同时和输入的数组a做判断,就解决了。

#include <stdio.h>
#include <stdlib.h>

#define max 100

typedef struct d{
	int data;
	struct d *left;
	struct d *right;
}tree;

tree *buildTree(int *a,int &n)
{
	int num=a[n++];
	if(num==NULL)
	{
		return NULL;
	}
	tree *t=(tree *)malloc(sizeof(tree));
	t->data=num;
	t->left=buildTree(a,n);
	t->right=buildTree(a,n);
	return t;
}

void post(tree *t)     //这里是递归的后序遍历
{
	if(t==NULL)
	{
		return;
	}
	post(t->left);
	post(t->right);
	printf("%d->",t->data);
}

bool postOrder(tree *t,int *orderArray,int len)      //这里是非递归的后序遍历进行检测
{
	tree *stack1[max];
	tree *stack2[max];
	int top1,top2;
	bool ret=false;
	top1=top2=-1;
	tree *tmp=t;
	while(top1!=-1||tmp!=NULL)
	{
		for(;tmp!=NULL;)
		{
			stack1[++top1]=tmp;
			stack2[++top2]=tmp;
			tmp=tmp->right;
		}
		if(top1!=-1)
		{
			tmp=stack1[top1--];
			tmp=tmp->left;
		}
	}
	int i;
	if(len>top2)
	{
		ret=false;
	}else
	{
		for(i=0;top2!=-1;top2--)
		{
			if(orderArray[i]==(stack2[top2]->data))
			{
			
				i++;
			}
		}
		if(i==len)
		{
			ret=true;
		}
	}
	
	return ret;
}


int main()
{
	int a[]={1,2,4,8,0,0,0,5,0,0,3,6,0,0,7,0,0,};      //用于创建树的数组
	int order[]={8,4,5,2};                             //检测用的数组1
	int orlen=sizeof(order)/sizeof(order[0]);
	int n=0;
	tree *t=buildTree(a,n);	
	post(t);
	printf("\n");
	bool ret=postOrder(t,order,orlen);
	printf("%d",ret);
        /*----------*/
        int order2[]={1,2,3};                              //检测用的数组2
        ret=postOrder(t,order2,orlen);
        printf("\n%d",ret);
}