package binarySortTree;
/*
* Java实现二叉排序树
*/
public class BinaryNode {
private int value;
private BinaryNode lChild;
private BinaryNode rChild;
public BinaryNode(int value, BinaryNode l, BinaryNode r) {
this.value = value;
this.lChild = l;
this.rChild = r;
}
public BinaryNode getLChild() {
return lChild;
}
public void setLChild(BinaryNode child) {
lChild = child;
}
public BinaryNode getRChild() {
return rChild;
}
public void setRChild(BinaryNode child) {
rChild = child;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public static void iterate(BinaryNode root) {
if (root.lChild != null) {
iterate(root.getLChild());
}
System.out.print(root.getValue() + " ");
if (root.rChild != null) {
iterate(root.getRChild());
}
}
public void addChild(int n) {
if (n < value) {
if (lChild != null) {
lChild.addChild(n);
} else {
lChild = new BinaryNode(n, null, null);
}
} else {
if (rChild != null) {
rChild.addChild(n);
} else {
rChild = new BinaryNode(n, null, null);
}
}
}
public static void main(String[] args) {
System.out.println();
int[] arr = new int[] { 23, 54, 1, 65, 9, 3, 100 };
BinaryNode root = new BinaryNode(arr[0], null, null);
for (int i = 1; i < arr.length; i++) {
root.addChild(arr[i]);
}
BinaryNode.iterate(root);
}
}
Java 二叉排序数
最新推荐文章于 2022-08-31 15:27:40 发布