• 二叉树遍历1


    题目描述

    编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。
    例如如下的先序遍历字符串:
    ABC##DE#G##F###
    其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。

    输入描述

    输入包括1行字符串,长度不超过100。

    输出描述

    可能有多组测试数据,对于每组数据,

    输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
    每个输出结果占一行。

    输入样例

    a#b#cdef#####
    a##
    

    输出样例

    a b f e d c 
    a 
    

    来源or类型

    数据结构高分笔记

    #include<iostream>
    #include<cstring>
    #include<string>
    #include<algorithm>
    using namespace std;
    
    char s[1000];
    
    struct node//定义节点 
    {
    	char data;
    	node *lchild;
    	node *rchild;
    };
    
    void creat(node * &root,int &index,int n )//用先去遍历的方式输入字符串构建树 
    {                                          //& 是引用符号 ,当需要创建节点时,就要用引用符号
    	if (index==n)                          //
    	return;
    	
    	if (s[index] == '#')//# 代表空树 
    	{
    		root = NULL;
    		index++;
    	}
    	else
    	{
    		root = new node; //不是空树就建立节点 
    		root->data = s[index];//赋值 
    		index++;
    		
    		creat(root->lchild , index,n);//用先序遍历 来进行赋值 
    		creat(root->rchild , index,n);
    		
    	}
    	return;
    }
    
    void inorder(node *root)//通过中序遍历打印树 
    {
    	if (root!=NULL)
    	{
    		inorder(root->lchild);
    		if (root->data!='#')
    		printf("%c ",root->data);
    		inorder(root->rchild);
    	}
    	return;
    }
    int main()
    {
    	int n,m,j,k,i,T;
    	while (gets(s)!=NULL)
    	{
    		node *root;//建树 
    		int index = 0;
    		int len = strlen(s);
    		index = 0;
    		creat(root,index,len);
    		inorder(root);
    		printf("
    ");
    	}		
    	
    	return 0;
    }
    
    
    
  • 相关阅读:
    BeagleBone Black安装小米随身WiFi驱动方法
    java-ee,ssh整合博文收藏
    BeagleBoneBlack Linux开发相关链接收藏
    Debian7.7 wheezy 中源码安装emacs24
    GLOG使用注意事项
    centos、linux改变ll命令显示颜色
    centos中samba配置后始终连不上的绝招
    中兴电信光纤猫F612管理员密码获取方法
    STM32W108芯片的SWD在IAR7.30版本中不能用
    TRF7960天线参数试验
  • 原文地址:https://www.cnblogs.com/Romantic-Chopin/p/12451310.html
Copyright © 2020-2023  润新知