请用递归方式实现二叉树的先序、中序和后序的遍历打印。 给定一个二叉树的根结点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) {
ArrayList pre=new ArrayList<TreeNode>();
ArrayList in=new ArrayList<TreeNode>();
ArrayList post=new ArrayList<TreeNode>();
preorder(root,pre);
inorder(root,in);
postorder(root,post);
int[][] nodes=new int[3][pre.size()];
for(int i=0;i<pre.size();++i){
nodes[0][i]=(Integer)pre.get(i);
nodes[1][i]=(Integer)in.get(i);
nodes[2][i]=(Integer)post.get(i);
}
return nodes;
}
public void preorder(TreeNode root,ArrayList<Integer> pre){
if(root==null){
return;
}
pre.add(root.val);
preorder(root.left,pre);
preorder(root.right,pre);
}
public void inorder(TreeNode root,ArrayList<Integer> in){
if(root==null){
return;
}
inorder(root.left,in);
in.add(root.val);
inorder(root.right,in);
}
public void postorder(TreeNode root,ArrayList<Integer> post){
if(root==null){
return;
}
postorder(root.left,post);
postorder(root.right,post);
post.add(root.val);
}
}