前序遍历:先遍历父节点,再遍历左节点,最后遍历右节点
中序遍历:先遍历左节点,在遍历父节点,最后遍历右节点
后序遍历:先遍历左节点,再遍历右节点,最后遍历父节点
针对以下二叉树进行前序遍历、中序遍历、后序遍历
public class BinaryTreeTraverse {
public static void main(String[] args) {
Node root = createTree();
BinaryTree tree = new BinaryTree(root);
System.out.println("============Preorder Traversal==================");
tree.preOrder();//1,2,3,5,4
System.out.println("============Inorder Traversal==================");
tree.inOrder();//2,1,5,3,4
System.out.println("============Postorder Traversal==================");
tree.postOrder();//2,5,4,3,1
}
public static Node createTree() {
Node root = new Node(1);
root.setLeft(new Node(2));
Node right = new Node(3);
right.setLeft(new Node(5));
right.setRight(new Node(4));
root.setRight(right);
return root;
}
}
class BinaryTree {
private Node root;
public BinaryTree(Node root) {
this.root = root;
}
public void preOrder() {
root.preOrder();
}
public void inOrder() {
root.inOrder();
}
public void postOrder() {
root.postOrder();
}
}
class Node {
private int id;
private Node left;
private Node right;
public Node(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
return "Node{" +
"id=" + id +
'}';
}
//前序遍历:先遍历父节点,再遍历左节点,最后遍历右节点
public void preOrder() {
System.out.println(this.getId());
if (this.left != null) {
this.left.preOrder();
}
if (this.right != null) {
this.right.preOrder();
}
}
//中序遍历:先遍历左节点,在遍历父节点,最后遍历右节点
public void inOrder() {
if (this.left != null) {
this.left.inOrder();
}
System.out.println(this.getId());
if (this.right != null) {
this.right.inOrder();
}
}
//后序遍历:先遍历左节点,再遍历右节点,最后遍历父节点
public void postOrder() {
if (this.left != null) {
this.left.postOrder();
}
if (this.right != null) {
this.right.postOrder();
}
System.out.println(this.getId());
}