public class BinaryTree {
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
print(root);
}
/**
* 先序遍历:访问根结点的操作发生在遍历其左右子树之前。 根节点 -> 左子树 -> 右子树 1 2 4 5 3 6 7
* 中序遍历:访问根结点的操作发生在遍历其左右子树中间。 左子树 -> 根节点 -> 右子树 4 2 5 1 6 3 7
* 后序遍历:访问根结点的操作发生在遍历其左右子树之后。 左子树 -> 右子树 -> 根节点 4 5 2 6 7 3 1
*
*/
public static void print(Node root) {
if (root == null) {
return;
}
// 先序遍历,这行是第一次来到该节点
// System.out.print(root.value + " ");
print(root.left);
// 中序遍历,这行是第二次来到该节点
// System.out.print(root.value + " ");
print(root.right);
// 后序遍历,这行是第三次来到该节点
System.out.print(root.value + " ");
}
public static class Node {
Node left;
Node right;
int value;
public Node(int value) {
this.value = value;
}
}
}