在二叉树中,共有三种遍历方法,分别是前序遍历、中序遍历、后序遍历。
前序遍历指的是按照根节点--左子节点--右子节点进行遍历;
中序遍历指的是按照左子节点--根节点--右子节点进行遍历;
后序遍历指的是按照左子节点--右子节点--根节点进行遍历。
按照上图构建二叉树后先序遍历结果为:1、2、3、5、4;中序遍历结果为:2、1、5、3、4;后序遍历结果为:2、5、4、3、1
public class Main {
public static void main(String[] args) {
Node node1 = new Node(1, "Amy");
Node node2 = new Node(2, "Bob");
Node node3 = new Node(3, "Candy");
Node node4 = new Node(4, "Doff");
Node node5 = new Node(5, "Emma");
BinaryTree tree = new BinaryTree();
tree.setRoot(node1);
node1.setLeft(node2);
node1.setRight(node3);
node3.setLeft(node5);
node3.setRight(node4);
System.out.println("前序遍历为:");
tree.preOrder();
System.out.println("中序遍历为:");
tree.infixOrder();
System.out.println("后序遍历为:");
tree.postOrder();
}
}
//节点
class Node {
private int id;
private String name;
Node left;
Node right;
public Node(int ID, String na) {
this.id = ID;
this.name = na;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
return "Node{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
//前序遍历
//根->左->右
public void preOrder() {
System.out.println(this);
if (this.left != null) {
this.left.preOrder();
}
if (this.right != null) {
this.right.preOrder();
}
}
//中序遍历
//左->根->右
public void infixOrder() {
if (this.left != null) {
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null) {
this.right.infixOrder();
}
}
//后序遍历
//左->右->根
public void postOrder() {
if (this.left != null) {
this.left.postOrder();
}
if (this.right != null) {
this.right.postOrder();
}
System.out.println(this);
}
}
//二叉树
class BinaryTree {
private Node root;
public void setRoot(Node root) {
this.root = root;
}
//前序遍历
public void preOrder() {
if (this.root != null) {
this.root.preOrder();
} else {
System.out.println("二叉树为空,无法遍历");
}
}
//中序遍历
public void infixOrder() {
if (this.root != null) {
this.root.infixOrder();
} else {
System.out.println("二叉树为空,无法遍历");
}
}
//后序遍历
public void postOrder() {
if (this.root != null) {
this.root.postOrder();
} else {
System.out.println("二叉树为空,无法遍历");
}
}
}
前序遍历为:
Node{id=1, name='Amy'}
Node{id=2, name='Bob'}
Node{id=3, name='Candy'}
Node{id=5, name='Emma'}
Node{id=4, name='Doff'}
中序遍历为:
Node{id=2, name='Bob'}
Node{id=1, name='Amy'}
Node{id=5, name='Emma'}
Node{id=3, name='Candy'}
Node{id=4, name='Doff'}
后序遍历为:
Node{id=2, name='Bob'}
Node{id=5, name='Emma'}
Node{id=4, name='Doff'}
Node{id=3, name='Candy'}
Node{id=1, name='Amy'}