zoukankan      html  css  js  c++  java
  • 已知先序中序求后序算法

    // tree.cpp : Defines the entry point for the console application.
    //
    
    #include <stdio.h>
    #include "string.h"
    
    typedef struct node
    {
    	char data;
    	struct node *lchild,*rchild;
    } BinNode;
    typedef BinNode *BinTree;
    BinNode *CreateNode(char c)
    {
    	BinNode *n1=new BinNode();
    	n1->data=c;
    	n1->lchild=NULL;
    	n1->rchild=NULL;
    	return n1;
    }
    int searchchar(char c,char *order)
    {
    	for(int i=0; i<strlen(order); i++)
    	{
    		if(c==order[i])
    			return i;
    	}
    	return -1;
    }
    
    BinNode *CreateTree(char *pre,char *in)
    {
    	char c=pre[0];
    	char temppre[100];
    	char tempin[100];
    	char *p;
    	int i=0;
    	BinNode *bnode;
    	if(pre=='')
    		return NULL;
    	memset(temppre,0,100);
    	memset(tempin,0,100);
    	bnode=CreateNode(c);
    	i=searchchar(pre[0],in);
    	if(i==-1)
    		return 0;
    	p=in;
    	strncpy(tempin,p,i);
    	p=pre;
    	strncpy(temppre,p+1,i);
    	bnode->lchild=CreateTree(temppre,tempin);//left
        memset(tempin,0,100);
    	memset(temppre,0,100);
    	p=in+i+1;
    	strncpy(tempin,p,strlen(in)-i);
    	p=pre+i+1;
    	strncpy(temppre,p,strlen(in)-i);
    	bnode->rchild=CreateTree(temppre,tempin); //right
    return bnode;
    }
    
    void POSTORDER(BinNode *t)
    {
    	if(t) 
    	{
    		POSTORDER(t->lchild); 
    		POSTORDER(t->rchild); 
    		printf("	%c",t->data);
    	}
    }
    
    int main(int argc, char *argv[])
    {
    	char preorder[100];
    	char inorder[100];
    	BinNode *Head;
    	do
    	{
    		printf("preorder sequence:
    ");
    		scanf("%s",preorder);
    		printf("inorder sequence:
    ");
    		scanf("%s",inorder);
    	}
    	while(strlen(preorder)!=strlen(inorder));
    	Head=CreateTree(preorder,inorder);
    	printf("post sequence:");
    	POSTORDER(Head);
    	printf("
    ");
    	//	printf("%ld",strlen(readin));
    return 0;
    }
    
    
  • 相关阅读:
    eclipse中编译出现错误undefined reference to `_sbrk'
    STM32L431驱动带UC1698芯片调试记录
    IAR里面STM32工程使用printf
    STM32L431仿真卡在HAL_InitTick(TICK_INT_PRIORITY);
    电信NB-IOT的温湿度采集器开发记录
    程序运行之ELF文件的段
    linux c编程:进程控制(二)_竞争条件
    ubuntun下安装Fiddler
    程序运行之目标文件(一)
    linux c编程:进程控制(一)
  • 原文地址:https://www.cnblogs.com/Skyxj/p/3478952.html
Copyright © 2011-2022 走看看