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

题目:

链式二叉树的创建及遍历
描述:
树的遍历有先序遍历、中序遍历和后序遍历。先序遍历的操作定义是先访问根结点,然后访问左子树,最后访问右子树。中序遍历的操作定义是先访问左子树,然后访问根,最后访问右子树。后序遍历的操作定义是先访问左子树,然后访问右子树,最后访问根。对于采用链式存储结构的二叉树操作中,创建二叉树通常采用先序次序方式输入二叉树中的结点的值,空格表示空树。对于如下的二叉树,我们可以通过如下输入"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();
        }
    }
}
相关推荐
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245034 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA4 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc4 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg14 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA4 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX4 天前
020-C++之unordered容器
数据结构·c++
岛雨QA4 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas4 天前
初识基本排序
java·数据结构·学习方法·排序