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

题目:

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


试根据输入创建对应的链式二叉树,并输入其先序、中序和后序遍历结果。
输入:
输入第一行为一个自然数n,表示用例个数
接下来为n行字符串,每行用先序方式输入的要求创建的二叉树结点,’-’表示前一结点的子树为空子树。
输出:
对每个测试用例,分别用三行依次输出其先序、中序和后序遍历结果。

样例输入:
1
abdh---e-i--cf-j--gk---

样例输出:
abdheicfjgk
hdbeiafjckg
hdiebjfkgca

代码:

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();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星与星熙.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值