题目链接
题目描述
题目描述
给出一个n个节点的二叉树,请求出二叉树的前序遍历,中序遍历和后序遍历。
输入描述
第一位一个整数n,第二个表示右儿子序号,如果该序号为0表示没有。 (例如下面示例中,F序号为1,C序号为2,E序号为3,A序号为4,D序号为5,G序号为6,B序号为7)
输出描述
共三行,第一行为二叉树的前序遍历,第二行为中序遍历,第三行为后序遍历
输入示例
7 F 2 3 C 4 5 E 0 6 A 0 0 D 7 0 G 0 0 B 0 0
输出示例
FCADBEG ACBDFEG ABDCGEF
算法示例
import java.util.Scanner;
public class Main{
public static class TreeNode{
String val;
TreeNode left;
TreeNode right;
TreeNode(){}
TreeNode(String val){
this.val = val;
this.left = null;
this.right = null;
}
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
if(n == 0) return;
String[][] arr = new String[n + 1][3];
for(int i = 1; i <= n; i++){
String[] temp = sc.nextLine().split(" ");
arr[i][0] = temp[0];
arr[i][1] = temp[1];
arr[i][2] = temp[2];
}
// 构造二叉树
TreeNode root = new TreeNode(arr[1][0]);
getTree(root, arr, 1);
prevPrint(root);
System.out.println();
midPrint(root);
System.out.println();
backPrint(root);
}
public static void getTree(TreeNode root, String[][] str, int idx){
int L = Integer.parseInt(str[idx][1]);
int R = Integer.parseInt(str[idx][2]);
if(L != 0){
TreeNode cur = new TreeNode(str[L][0]);
root.left = cur;
getTree(cur, str, L);
}
if(R != 0){
TreeNode cur = new TreeNode(str[R][0]);
root.right = cur;
getTree(cur, str, R);
}
}
public static void prevPrint(TreeNode root){
if(root == null) return;
System.out.print(root.val);
prevPrint(root.left);
prevPrint(root.right);
}
public static void midPrint(TreeNode root){
if(root == null) return;
midPrint(root.left);
System.out.print(root.val);
midPrint(root.right);
}
public static void backPrint(TreeNode root){
if(root == null) return;
backPrint(root.left);
backPrint(root.right);
System.out.print(root.val);
}
}