请用递归方式实现二叉树的先序、中序和后序的遍历打印。
给定一个二叉树的根结点root,请依次返回二叉树的先序,中序和后续遍历(二维数组的形式)。
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class TreeToSequence {
public int[][] convert(TreeNode root) {
List<Integer> first = new LinkedList<Integer>();
List<Integer> middle = new LinkedList<Integer>();
List<Integer> back = new LinkedList<Integer>();
getFirst(first, root);
getMiddle(middle, root);
getBack(back, root);
int[][] result = new int[3][first.size()];
for (int i = 0; i < first.size(); i++) {
result[0][i] = first.get(i);
result[1][i] = middle.get(i);
result[2][i] = back.get(i);
}
return result;
}
public void getFirst(List<Integer> first, TreeNode root) {
if (root == null)
return;
first.add(root.val);
getFirst(first, root.left);
getFirst(first, root.right);
}
public void getMiddle(List<Integer> first, TreeNode root) {
if (root == null)
return;
getMiddle(first, root.left);
first.add(root.val);
getMiddle(first, root.right);
}
public void getBack(List<Integer> first, TreeNode root) {
if (root == null)
return;
getBack(first, root.left);
getBack(first, root.right);
first.add(root.val);
}
}