内容:先序遍历、中序遍历和后序遍历(递归)。
代码实现:
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,"许六");
BinaryTree binaryTree = new BinaryTree();
root.setLeft(node2);
root.setRight(node3);
node3.setRight(node4);
node3.setLeft(node5);
binaryTree.setRoot(root);
binaryTree.preorder();
System.out.println("=========");
binaryTree.infixorder();
System.out.println("=========");
binaryTree.postorder();
}
}
//创建结点
class Node {
private int sign;
private String name;
private Node left;
private Node right;
public Node(int sign, String name) {
this.sign = sign;
this.name = name;
}
public int getSign() {
return sign;
}
public void setSign(int sign) {
this.sign = sign;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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{" +
"sign=" + sign +
", 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) {
System.out.println("该二叉树为空,无法进行遍历");
} else {
this.root.preorder();
}
}
public void infixorder() {
if(root == null) {
System.out.println("该二叉树为空,无法进行遍历");
} else {
this.root.infixorder();
}
}
public void postorder() {
if(root == null) {
System.out.println("该二叉树为空,无法进行遍历");
} else {
root.postorder();
}
}
}