PAT1043 BST 镜像管不了了

考虑到 出现相同的数等等

#include<stdio.h>
#include<stdlib.h>
int cache[1001];
int read=0,n;
struct node*root;
struct node{
	int value;
	struct node* father;
	struct node* lchild;
	struct node* rchild;
};
void BuildTree(struct node*&Node,struct node*father){
	Node=(struct node*)malloc(sizeof(struct node));
    Node->lchild=Node->rchild=NULL;
	if(read==0) Node->father=NULL; //头节点
    else Node->father=father;	
    Node->value=cache[read++];
	
	
	while(read<n){
		/*if(Node->father&&Node->father->lchild==Node&&cache[read]>Node->father->value)// 
		break;
		if(Node->father&&Node->father->rchild==Node&&cache[read]<Node->father->value)
		break;*/
		father=Node;//不好的习惯 一个变量两用 father改变用法了 
		while(father->father){//???
			if(father->father->lchild==father&&cache[read]<father->father->value)
			father=father->father;
			else if(father->father->rchild==father&&cache[read]>=father->father->value)
			father=father->father;
			else
			return ;
		}
		if(cache[read]<Node->value)
		BuildTree(Node->lchild,Node);
		else
		BuildTree(Node->rchild,Node);
	}
}
void postorder1(struct node*Node){
	if(Node==NULL)
	return;

	postorder1(Node->lchild);
	postorder1(Node->rchild);
	
	if(read==n)
    read=0;
    else
    printf(" ");
    
	printf("%d",Node->value); 
};

void postorder2(struct node*Node){
	if(Node==NULL)
	return;
	
	postorder2(Node->lchild); 
	postorder2(Node->rchild);
	
	
	if(root!=Node)
	printf(" ");
	 
	printf("%d",-Node->value);
};

int main(){
	int mirror=1;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	scanf("%d",cache+i);
	
	if(cache[1]<cache[0])//判断是不是镜像 
	mirror=0;
	for(int i=0;i<n;i++)
	if(cache[i]<cache[1])
	mirror=0;
	
	if(mirror){//若是镜像 做负数处理 便于建BST 
		for(int i=0;i<n;i++)
		cache[i]=-cache[i];
	}
	
	BuildTree(root,root);
	
	if(read<n)
	printf("NO\n");
	else{
		printf("YES\n");
		if(mirror==0)
		postorder1(root);
		else
		postorder2(root);
	}
	return 0;
}

  

posted on 2016-09-22 21:36  SijingLin  阅读(138)  评论(0编辑  收藏  举报

导航