package test3; public class Test_A27 { // 前序遍历(根-左-右) public void preOrderTraversal(TreeNode root){ if(root==null){ return; } System.out.println(root.val+""); preOrderTraversal(root.left); preOrderTraversal(root.right); } // 中序遍历(左-根-右) public void inOrderTraversal(TreeNode root){ if(root==null){ return; } preOrderTraversal(root.left); System.out.println(root.val+""); preOrderTraversal(root.right); } // 后序遍历(左-右-根) public void postOrderTraversal(TreeNode root){ if(root==null){ return; } preOrderTraversal(root.left); preOrderTraversal(root.right); System.out.println(root.val+""); } public static void main(String[] args){ TreeNode root=new TreeNode(11); TreeNode root2=new TreeNode(21); TreeNode root3=new TreeNode(31); TreeNode root4=new TreeNode(41); TreeNode root5=new TreeNode(51); TreeNode root6=new TreeNode(61); root.left=root2; root.right=root3; root2.left=root4; root2.right=root5; root3.right=root6; Test_A27 traversal=new Test_A27(); System.out.println("前序遍历结果:"); traversal.preOrderTraversal(root); System.out.println("中序遍历结果:"); traversal.inOrderTraversal(root); System.out.println("后序遍历结果:"); traversal.postOrderTraversal(root); } } class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int val){ this.val=val; } }