链式二叉树的创建及遍历
描述:
树的遍历有先序遍历、中序遍历和后序遍历。先序遍历的操作定义是先访问根结点,然后访问左子树,最后访问右子树。中序遍历的操作定义是先访问左子树,然后访问根,最后访问右子树。后序遍历的操作定义是先访问左子树,然后访问右子树,最后访问根。对于采用链式存储结构的二叉树操作中,创建二叉树通常采用先序次序方式输入二叉树中的结点的值,空格表示空树。对于如下的二叉树,我们可以通过如下输入“AE-F--H--”得到( ‘-’表示空子树)。
试根据输入创建对应的链式二叉树,并输入其先序、中序和后序遍历结果。
输入:
输入第一行为一个自然数n,表示用例个数
接下来为n行字符串,每行用先序方式输入的要求创建的二叉树结点,’-’表示前一结点的子树为空子树。
输出:
对每个测试用例,分别用三行依次输出其先序、中序和后序遍历结果。
样例输入:
1
abdh---e-i--cf-j--gk---
样例输出:
abdheicfjgk
hdbeiafjckg
hdiebjfkgca
图片如下:
代码如下:
import java.util.Scanner; public class erTree { public static int number; public static class Node { char me; Node lchild; Node rchild; public Node() { this.lchild = null; this.rchild = null; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int treenumber = sc.nextInt(); while (treenumber-- != 0) { String s = sc.next(); Node head = new Node(); number = 0; head = bulidTree(head, s, s.length()); xian(head); System.out.println(); zhong(head); System.out.println(); hou(head); System.out.println(); } } private static Node bulidTree(Node head, String s, int length) { if ( length == number) return null; if(s.charAt(number)=='-') { head = null; number++; } else{ head = new Node(); head.me = s.charAt(number); number++; head.lchild = bulidTree(head.lchild, s, length); head.rchild = bulidTree(head.rchild, s, length); } return head; } public static void hou(Node search) { if (search == null) return; hou(search.lchild); hou(search.rchild); System.out.print(search.me); } public static void zhong(Node search) { if (search == null) return; zhong(search.lchild); System.out.print(search.me); zhong(search.rchild); } public static void xian(Node head) { if (head == null) return; System.out.print(head.me); xian(head.lchild); xian(head.rchild); } }