二叉树的前序、中序、后序遍历
-
前序遍历: 先输出父节点,再遍历左子树和右子树。
-
中序遍历: 先遍历左子树,再输出父节点,再遍历右子树。
-
后序遍历; 先遍历左子树,再遍历右子树,最后输出父节点。
-
代码实现:
//需求:遍历上图中的二叉树
public class BinaryTreeDemo {
public static void main(String[] args) {
// 手动构建二叉树
Node root = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
root.setLeft(node2);
root.setRight(node3);
node3.setLeft(node4);
node3.setRight(node5);
BinaryTree binaryTree = new BinaryTree(root);
// 前序遍历二叉树
//binaryTree.preOrder(); // 1 2 3 4 5
// 中序遍历二叉树
//binaryTree.infixOrder(); // 2 1 4 3 5
// 后序遍历二叉树
binaryTree.postOrder(); // 2 4 5 3 1
}
}
/**
* 定义二叉树
*/
class BinaryTree {
// 二叉树的根节点
private Node root;
public BinaryTree(Node root) {
this.root = root;
}
// 前序遍历
public void preOrder() {
if (root == null) {
System.out.println("此二叉树为空!");
} else {
root.preOrder();
}
}
// 中序遍历
public void infixOrder() {
if (root == null) {
System.out.println("此二叉树为空!");
} else {
root.infixOrder();
}
}
// 后序遍历
public void postOrder() {
if (root == null) {
System.out.println("此二叉树为空!");
} else {
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);
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);
}
}