链式二叉树的创建及遍历(数据结构实训)

题目:

链式二叉树的创建及遍历
描述:
树的遍历有先序遍历、中序遍历和后序遍历。先序遍历的操作定义是先访问根结点,然后访问左子树,最后访问右子树。中序遍历的操作定义是先访问左子树,然后访问根,最后访问右子树。后序遍历的操作定义是先访问左子树,然后访问右子树,最后访问根。对于采用链式存储结构的二叉树操作中,创建二叉树通常采用先序次序方式输入二叉树中的结点的值,空格表示空树。对于如下的二叉树,我们可以通过如下输入"AE-F--H--"得到( '-'表示空子树)。

试根据输入创建对应的链式二叉树,并输入其先序、中序和后序遍历结果。

输入:

输入第一行为一个自然数n,表示用例个数

接下来为n行字符串,每行用先序方式输入的要求创建的二叉树结点,'-'表示前一结点的子树为空子树。

输出:

对每个测试用例,分别用三行依次输出其先序、中序和后序遍历结果。
样例输入:

1

abdh---e-i--cf-j--gk---
样例输出:

abdheicfjgk

hdbeiafjckg

hdiebjfkgca

代码:

java 复制代码
import java.util.Scanner;

public class Xingyuxingxi {
    static String str;//将字符串设为全局变量,就不需要导入到方法中
    static int cnt;
    static TreeNode root;
    public static class TreeNode{
        char item;
        TreeNode lc;
        TreeNode rc;
        public TreeNode(char item)
        {
            this.item=item;
        }
    }
    public static void csh()//初始化
    {
        root=null;
        cnt=-1;
    }
    public static TreeNode build(TreeNode root)
    {
        cnt++;
        TreeNode node=new TreeNode(str.charAt(cnt));
        if(cnt<str.length()&&node.item!='-')
        {
            root=node;
            //先左后右,先一路向左,遇到'-'后返回,再进右边
            root.lc=build(root.lc);
            root.rc=build(root.rc);
        }
        else
        {
            root=null;
        }
        return root;
    }
    public static void pre(TreeNode root)//先序
    {
        if(root==null)
        {
            return;
        }
        System.out.print(root.item);
        pre(root.lc);
        pre(root.rc);
    }
    public static void in(TreeNode root)//中序
    {
        if(root==null)
        {
            return;
        }
        in(root.lc);
        System.out.print(root.item);
        in(root.rc);
    }
    public static void post(TreeNode root)//后序
    {
        if(root==null)
        {
            return;
        }
        post(root.lc);
        post(root.rc);
        System.out.print(root.item);
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        while(a--!=0)
        {
            csh();
            str=sc.next();
            root=build(root);
            pre(root);
            System.out.println();
            in(root);
            System.out.println();
            post(root);
            System.out.println();
        }
    }
}
相关推荐
zaizai10072 小时前
算法(左程云)1
数据结构
charliejohn3 小时前
计算机考研 408 数据结构 图论-关键路径
数据结构·图论
David猪大卫19 小时前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
vvilkim20 小时前
数据结构类型、区别与应用场景:一篇讲透选型逻辑
数据结构
阿卡好可爱1 天前
Lua 热更新不生效:改完文件线上仍是旧逻辑,package.loaded 与 upvalue 重绑定详解
数据结构·分布式·后端·架构·lua
心仪久了会沦陷2 天前
C语言数据结构入门——树与二叉树详解:概念、堆实现与链式遍历
c语言·数据结构·算法
码少女2 天前
数据结构——图的基础
数据结构
Severus_black2 天前
【C++初阶】list使用及相关实现,思路顺滑流畅!
c语言·数据结构·c++·stl·list
二本咕咕-机械转码2 天前
FreeRTOS深入解析(八)IPC机制之FromISR详解
数据结构·单片机·链表