二叉树排序算法模拟实现

时间:2021-04-06 17:32:25
package ErChaTreePackage;

class Node {
public int num;
private Node left;
private Node right;

public Node(int num) {
this.num = num;
}

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;
}

}

class TreeSort {
private Node[] nodes;

public TreeSort(Node[] nodes) {
this.nodes = nodes;
}

public void sort(Node nodeO, Node nodeC) {
if (nodeC.num < nodeO.num) {
if (nodeO.getLeft() != null) {
sort(nodeO.getLeft(), nodeC);
} else {
nodeO.setLeft(nodeC);
}
} else {
if (nodeO.getRight() != null) {
sort(nodeO.getRight(), nodeC);
} else {
nodeO.setRight(nodeC);
}
}
}

public Node[] getSortNode() {
for (int i = 1; i < nodes.length; i++) {
sort(nodes[0], nodes[i]);
}
return nodes;
}

public void printSortNode(Node node) {//輸出的時候采用中續排列
if (node.getLeft() != null) {
printSortNode(node.getLeft());
}
System.out.println(node.num);
if (node.getRight() != null) {
printSortNode(node.getRight());
}
}

}

public class ErChaTree {
public static void main(String[] args) {
Node[] nodes = { new Node(8), new Node(4), new Node(3), new Node(5), new Node(9), new Node(6) };
TreeSort ts = new TreeSort(nodes);
nodes = ts.getSortNode();
ts.printSortNode(nodes[0]);
}

}

期中需要注意的是,输出采用左中右形式(中序)输出,方法就是先输出左子树 节点 右子树。