問題描述
已知二叉樹的一個按先序遍歷輸入的字符序列,如abc,de,g,f, (其中,表示空結點)。請建立二叉樹並按中序和後序的方式遍歷該二叉樹。
輸入
連續輸入多組數據,每組數據輸入一個長度小於50個字符的字符串。
輸出
每組輸入數據對應輸出2行:
第1行輸出中序遍歷序列;
第2行輸出後序遍歷序列。
樣例輸入
abc,,de,g,,f,,,
樣例輸出
cbegdfa
cgefdba
AC代碼
import java.util.*;
public class Main{
public static void main(String[] args){
MyTree myTree = new MyTree();
while (true){
myTree.getData();
TreeNode root= myTree.createTree(null);
myTree.visitInOrder(root);
System.out.println();
myTree.visitPostOrder(root);
System.out.println();
myTree.index = 0;
}
}
}
class TreeNode{
char val;
TreeNode left;
TreeNode right;
}
class MyTree{
String s;
Scanner scanner = new Scanner(System.in);
int index = 0;
public void getData(){
s = scanner.nextLine();
}
public TreeNode createTree(TreeNode root){
// 先序建樹
if(index == s.length()){
return null;
}
if(s.charAt(index) == ','){
index++;
return null;
}
root = new TreeNode();
root.val = s.charAt(index++);
root.left = createTree(root.left);
root.right = createTree(root.right);
return root;
}
public void visitPreOrder(TreeNode root){
// 先序遍歷
if(root != null){
System.out.print(root.val);
visitPreOrder(root.left);
visitPreOrder(root.right);
}
}
public void visitInOrder(TreeNode root){
// 中序遍歷
if(root != null){
visitInOrder(root.left);
System.out.print(root.val);
visitInOrder(root.right);
}
}
public void visitPostOrder(TreeNode root){
// 後續遍歷
if(root != null){
visitPostOrder(root.left);
visitPostOrder(root.right);
System.out.print(root.val);
}
}
}