先序遍历:根左右
中序遍历:左根右
后序遍历:左右根
//定义二叉树
public class Node {
int val;
Node left;
Node right;
Node(int data) {
this.val = data;
//先序遍历
public static void preOrderRecur(Node head) {
if(head ==null)
return;
System.out.print(head.val+" ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
//中序遍历
public static void inOrderRecur(Node head) {
if (head == null) {
return;
}
inOrderRecur(head.left);
System.out.print(head.val+" ");
inOrderRecur(head.right);
}
//后序遍历
public static void posOrderRecur(Node head) {
if (head == null) {
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
递归版本没什么好解释的啦。。。
只要记得当遍历到根节点时进行打印操作就行了,左右就直接进行递归。