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
");
	else{
		printf("YES
");
		if(mirror==0)
		postorder1(root);
		else
		postorder2(root);
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/lsj2020/p/5898061.html