Loading

第十三题、链式二叉树的创建及遍历(难度系数100)

链式二叉树的创建及遍历
描述:
树的遍历有先序遍历、中序遍历和后序遍历。先序遍历的操作定义是先访问根结点,然后访问左子树,最后访问右子树。中序遍历的操作定义是先访问左子树,然后访问根,最后访问右子树。后序遍历的操作定义是先访问左子树,然后访问右子树,最后访问根。对于采用链式存储结构的二叉树操作中,创建二叉树通常采用先序次序方式输入二叉树中的结点的值,空格表示空树。对于如下的二叉树,我们可以通过如下输入“AE-F–H–”得到( ‘-’表示空子树)。
在这里插入图片描述
试根据输入创建对应的链式二叉树,并输入其先序、中序和后序遍历结果。
输入:
输入第一行为一个自然数n,表示用例个数
接下来为n行字符串,每行用先序方式输入的要求创建的二叉树结点,’-’表示前一结点的子树为空子树。
输出:
对每个测试用例,分别用三行依次输出其先序、中序和后序遍历结果。
样例输入:

1
abdh---e-i--cf-j--gk---

样例输出:

abdheicfjgk
hdbeiafjckg
hdiebjfkgca

参考:


import java.util.*;

public class Main {
    private static class Node{
        char value;
        Node lchild, rchild;

        public Node(char value) {
            this.value = value;
        }
    }
    private static Node root = null;
    // 用来标记当前创建到哪了
    private static int id;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        while (n-- > 0) {
            String str = sc.next();
            id = -1;
            root = create(root, str);
            pre_order();
            in_order();
            post_order();
        }
    }
    public static Node create(Node root, String str) {
        ++id;
        if (id < str.length() && str.charAt(id) != '-') {
            root = new Node(str.charAt(id));
            root.lchild = create(root.lchild, str);
            root.rchild = create(root.rchild, str);
        } else {
            root = null;
        }
        return root;
    }
    // 前序遍历
    public static void pre_order() {
        pre_order(root);
        System.out.println();
    }
    private static void pre_order(Node root) {
        if (root != null) {
            System.out.print(root.value);
            pre_order(root.lchild);
            pre_order(root.rchild);
        }
    }
    // 中序遍历
    public static void in_order() {
        in_order(root);
        System.out.println();
    }
    private static void in_order(Node root) {
        if (root != null) {
            in_order(root.lchild);
            System.out.print(root.value);
            in_order(root.rchild);
        }
    }
    // 后序遍历
    public static void post_order() {
        post_order(root);
        System.out.println();
    }
    private static void post_order(Node root) {
        if (root != null) {
            post_order(root.lchild);
            post_order(root.rchild);
            System.out.print(root.value);
        }
    }
}
posted @ 2023-02-20 18:22  qing影  阅读(17)  评论(0)    收藏  举报  来源