二叉排序树的创建和遍历排序
直接看代码的注解详细说明 1:先创建二叉树的节点
class Node{
int value;
Node left;
Node right;
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
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 infixOrder(){
if (this.left != null){
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null){
this.right.infixOrder();
}
}
}
2:创建二叉排序树
class BinarySortTree{
private Node root;
public void add(Node node){
if (root == null){
root = node;
}else {
root.add(node);
}
}
public void infixOrder(){
if (root != null){
root.infixOrder();
}else {
System.out.println("二叉排序树为空");
}
}
}
3:测试类
public class BinarySortTreeDemo {
public static void main(String[] args) {
int[] arr = {7,3,10,12,5,1,9};
BinarySortTree binarySortTree = new BinarySortTree();
for (int i = 0; i < arr.length; i++) {
binarySortTree.add(new Node(arr[i]));
}
System.out.println("========二叉树排序=========");
binarySortTree.infixOrder();
}
}
========二叉树排序=========
Node{value=1}
Node{value=3}
Node{value=5}
Node{value=7}
Node{value=9}
Node{value=10}
Node{value=12}
|