前序:根-左-右
中序:左-根-右
后序:左-右-根
实现:
class TreeNode1 {
int val = 0;
TreeNode1 left = null;
TreeNode1 right = null;
public TreeNode1(int val) {
this.val = val;
}
}
public class printTree {
public static void main(String[] args) {
TreeNode1 A=new TreeNode1(1);
TreeNode1 B=new TreeNode1(2);
TreeNode1 C=new TreeNode1(3);
TreeNode1 D=new TreeNode1(4);
TreeNode1 E=new TreeNode1(5);
TreeNode1 F=new TreeNode1(6);
A.left=B;A.right=C;
B.left=D;B.right=E;
C.left=null;C.right=F;
D.left=null;D.right=null;
E.left=null;E.right=null;
F.left=null;F.right=null;
System.out.print("前序遍历结果:");
preTree(A);
System.out.println();
System.out.print("中序遍历结果:");
inTree(A);
System.out.println();
System.out.print("后序遍历结果:");
postTree(A);
}
static void preTree(TreeNode1 root){//前序遍历
if(root==null){
return;
}
System.out.print(root.val+" ");
if(root.left!=null){
preTree(root.left);
}
if(root.right!=null){
preTree(root.right);
}
}
static void inTree(TreeNode1 root){//中序遍历
if(root.left!=null){
inTree(root.left);
}
System.out.print(root.val+" ");
if(root.right!=null){
inTree(root.right);
}
}
static void postTree(TreeNode1 root){//后序遍历
if(root.left!=null){
inTree(root.left);
}
if(root.right!=null){
inTree(root.right);
}
System.out.print(root.val+" ");
}
}