二插排序树的插入,查找,中序遍历代码java实现

节点实体类

/**
 * @author cx
 * @Time 2020/3/11 16:44
 * @Description 节点实体类 相当于c中的结构体
 */
public class Node {
    private int value;

    private Node left;

    private Node right;

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

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

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

主函数实现

/**
 * @author cx
 * @Time 2020/3/11 16:35
 * @Description 二叉排序树
 */
public class BTsort {
    /**
     * @description 将指定的元素插入二插排序树中
     *
     * @param root
     * @param key
     * @return null
     */
    public static void BinarySort(Node root,int key)
    {
        /**获得根节点中的元素*/
        int value = root.getValue();
            if (key < value)
            {
                if (root.getLeft() == null)
                {
                    Node node = new Node(key);
                    root.setLeft(node);
                }
                else
                {
                    BinarySort(root.getLeft(),key);
                }
            }
            else if (key > value)
            {
                if (root.getRight() == null)
                {
                    Node node = new Node(key);
                    root.setRight(node);
                }else
                {
                    BinarySort(root.getRight(), key);
                }
            }
    }

    /**
     * @description 遍历二叉树找到查找的值
     *
     * @param root
     * @param key
     * @return true or false
     */
    public static boolean BinarySearch(Node root,int key)
    {
        if (root == null) return false;
        else if (root.getValue() == key) return true;
        else if (root.getValue() > key) return BinarySearch(root.getLeft(),key);
        else  return BinarySearch(root.getRight(),key);
    }

    /**
     * @description 中序遍历二叉树
     *
     * @param root
     * @return null
     */
    public static void inOrder(Node root)
    {
        if (root != null)
        {
            inOrder(root.getLeft());
            System.out.print(root.getValue()+" ");
            inOrder(root.getRight());
        }
    }

    public static void main(String[] args) {
        int[] array = {19,12,3,22,6,7,21,11,43};
        Node root = new Node(array[0]);
        for (int i = 1; i < array.length; i++)
        {
            BinarySort(root,array[i]);
        }
        if (BinarySearch(root,12))
        {
            System.out.println("二叉树中存在此元素!");
        }else
        {
            System.out.println("二叉树中不存在此元素!");
        }
        System.out.print("二叉树中序遍历:");
        inOrder(root);
    }

}

运行结果:
二插排序树的插入,查找,中序遍历代码java实现_第1张图片

你可能感兴趣的:(数据结构java实现,数据结构)