要点:
构建二叉排序树,递归函数add方法:
小于根节点,则右节点递归调用add方法。
大于等于根节点,则左节点递归调用add方法。
遍历二叉排序树:递归遍历view方法:
前序:先输出根节点,然后左节点递归调用view方法,最后右节点递归调用view方法。
中序:先左节点递归调用view方法,然后输出根节点,最后右节点递归调用view方法。
后序:先右节点递归调用view方法,然后左节点递归调用view方法,最后输出根节点。
代码:
public class BinarySortTreeExample {
public static void main(String[] args) {
int[] arr = {7, 3, 10, 12, 5, 6, 1, 9, 8};
BinarySortTree binarySortTree = new BinarySortTree();
for (int i = 0; i < arr.length; i++) {
binarySortTree.add(new Node(arr[i]));
}
System.out.println("前序遍历二叉树");
binarySortTree.prefixOrder();
System.out.println("中序遍历二叉树");
binarySortTree.infixOrder();
System.out.println("后序遍历二叉树");
binarySortTree.postfixOrder();
}
}
class BinarySortTree {
private Node root;
public void add(Node node) {
if (root == null) {
root = node;
} else {
root.add(node);
}
}
public void prefixOrder() {
if (root != null) {
root.prefixOrder();
} else {
System.out.println("二叉树为空");
}
}
public void infixOrder() {
if (root != null) {
root.infixOrder();
} else {
System.out.println("二叉树为空");
}
}
public void postfixOrder() {
if (root != null) {
root.postfixOrder();
} else {
System.out.println("二叉树为空");
}
}
}
class Node {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
public void add(Node node) {
if (node == null) {
return;
}
if (node.value < this.value) {
if (this.left == null) {
this.left = node;
} else {
this.left.add(node);
}
} else {
if (this.right == null) {
this.right = node;
} else {
this.right.add(node);
}
}
}
public void prefixOrder() {
System.out.println(this);
if (this.left != null) {
this.left.prefixOrder();
}
if (this.right != null) {
this.right.prefixOrder();
}
}
public void infixOrder() {
if (this.left != null) {
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null) {
this.right.infixOrder();
}
}
public void postfixOrder() {
if (this.left != null) {
this.left.postfixOrder();
}
if (this.right != null) {
this.right.postfixOrder();
}
System.out.println(this);
}
@Override
public String toString() {
return "Node value=" + this.value;
}
}