zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java实现二叉排序树

JAVA排序 实现 二叉
2023-09-14 09:13:18 时间

Java实现二叉排序树

1.源码如下:

  • BinarySortTree类
package Util;
/*
1.实现二叉排序树
 */
public class BinarySortTree {

    public Node addNode(Node root,int data){
        Node node = new Node(data);
        if(root == null){//第一次插入时,root必为空
            root = node;//让root指向新new出来的node
            return root;
        }
        Node temp = root;
        Node pre = root;
        int flag = -1;//左边为0,右边为1
        while(temp != null){
            if(temp.getData() == data)   return root;//如果相等,则不插入
            else if(temp.getData() > data){//如果当前的值大于插入的值,则遍历左子树
                pre = temp;
                temp = temp.getlChild();
                flag = 0;
            }
            else{
                pre = temp;
               temp = temp.getrChild();//进入右子树
                flag = 1;
            }
        }

        //根据标志决定是往哪个子树添加值
        if(flag == 0)
            pre.setlChild(node);//指向node
        if(flag == 1)
            pre.setrChild(node);
        flag = -1;
        return root;
    }


    //中序遍历
    //对于中序遍历,二叉排序树的输出有序数列
    public void traverseBinarySortTree(Node root){
        if(root.getlChild()!=null)//如果左孩子不为空
            traverseBinarySortTree(root.getlChild());//先遍历左子树
        System.out.println(root.getData());
        if(root.getrChild()!=null)
            traverseBinarySortTree(root.getrChild());
    }
}
  • Node类
package Util;

/**
 * 1.节点类型
 */
class Node{
    private int data;//二叉树中存储的是int型的数字
    private Node lChild = null;//存储左指针【指向左孩子】
    private Node rChild = null;//存储右指针【指向右孩子】

    Node(int data){
        this.data = data;//构造注入 data
    }

    Node(){

    }
    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getlChild() {
        return lChild;
    }

    public void setlChild(Node lChild) {
        this.lChild = lChild;
    }

    public Node getrChild() {
        return rChild;
    }

    public void setrChild(Node rChild) {
        this.rChild = rChild;
    }
}
  • Test类
public class Test{
    public static void main(String[] args) {
        BinarySorTree binarySorTree = new BinarySorTree();

        Node node = null;
        node = binarySorTree.addNode(node,4);
        binarySorTree.addNode(node,2);
        binarySorTree.addNode(node,5);
        binarySorTree.addNode(node, 1);
        binarySorTree.traverseBinarySortTree(node);
    }
}