class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Code {
public static void main(String[] args) {
TreeNode node1 = new TreeNode(7);
TreeNode node2 = new TreeNode(6);
TreeNode node3 = new TreeNode(5);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(3,node2,node1);
TreeNode node6 = new TreeNode(2,node4,node3);
TreeNode treeNode = new TreeNode(1,node6,node5);
//新建一个二叉树[1,2,3,4,5,6]
System.out.print("前序遍历:");
preorderTraversal(treeNode);
System.out.println();
System.out.print("中序遍历:");
mediumOrderTraversal(treeNode);
System.out.println();
System.out.print("后序遍历:");
postorderTraversal(treeNode);
}
/**
* 前序遍历
* @param root
*/
public static void preorderTraversal(TreeNode root) {
if (root != null) {
System.out.print(root.val + " ");
preorderTraversal(root.left);
preorderTraversal(root.right);
}
}
/**
* 中序遍历
* @param root
*/
public static void mediumOrderTraversal(TreeNode root) {
if (root != null) {
mediumOrderTraversal(root.left);
System.out.print(root.val + " ");
mediumOrderTraversal(root.right);
}
}
/**
* 后序遍历
* @param root
*/
public static void postorderTraversal(TreeNode root) {
if (root != null) {
postorderTraversal(root.left);
postorderTraversal(root.right);
System.out.print(root.val + " ");
}
}
}