class="java" name="code">import java.util.Scanner; class Node { public String value; // 字母节点 public Node left, right;// 左右子节点 static String getChar() { Scanner sc = new Scanner(System.in); return sc.next(); } static void createTree(Node t) { String c = getChar(); if ("0".equals(c)) { t.value = "0"; } else { t.value = c; t.left = new Node(); createTree(t.left); t.right = new Node(); createTree(t.right); } } static void preOrder(Node t) { if(null != t) { System.out.print(t.value + " "); preOrder(t.left); preOrder(t.right); } } static void lastOrder(Node t) { if(null != t) { lastOrder(t.left); lastOrder(t.right); System.out.print(t.value + " "); } } public static void main(String[] args) { Node t = new Node(); createTree(t); System.out.println("t"); System.out.print("先序遍历:"); preOrder(t); System.out.println(); System.out.print("后序遍历:"); lastOrder(t); } }
使用0代表节点结束。
输入值:
123
l
0
0
right
0
0
?
输出结果:
t
先序遍历:123 l 0 0 right 0 0?
后序遍历:0 0 l 0 0 right 123
?直接使用console进行测试结果截图:
?
?