public class BinarySortTreeDemo {
public static void main(String[] args) {
int[] array = {7, 3, 10, 12, 5, 1, 9};
BinaryTree binaryTree = new BinaryTree();
for (int i = 0; i < array.length; i++) {
binaryTree.add(new Node(array[i]));
}
binaryTree.infixOrder();
}
}
class BinaryTree {
private Node root;
public void add(Node node) {
if(this.root == null) {
root = node;
} else {
root.add(node);
}
}
public void infixOrder() {
if(root != null) {
root.infixOrder();
} else {
System.out.println("二叉树为空~");
}
}
}
class Node {
public int num;
public Node left;
public Node right;
public Node(int num) {
this.num = num;
}
@Override
public String toString() {
return num + "";
}
public void infixOrder() {
if (this.left != null) {
this.left.infixOrder();
}
System.out.print("=>" + this);
if (this.right != null) {
this.right.infixOrder();
}
}
public void add(Node node) {
if(node == null) {
return;
}
if(node.num < this.num) {
if(this.left != null) {
this.left.add(node);
} else {
this.left = node;
}
} else {
if(this.right != null) {
this.right.add(node);
} else {
this.right = node;
}
}
}
}
二叉排序树递归实现
最新推荐文章于 2023-12-08 13:11:09 发布