二叉查找(排序)树

此生再无相见时 提交于 2020-01-29 01:57:35
package four_tree.binarySearchTree;

/**
 * Author:jinpma
 * Date :2019/12/22
 */
public class BinarySearchTree
{
    public static void main(String[] args)
    {
        int array[] = {7,3,10,12,5,1,9,2};
        BinaryTreeDemo bt = new BinaryTreeDemo();
        for (int i = 0; i < array.length; i++)
        {
            bt.add(new Node(array[i]));
        }
        bt.inOrder();
    }
    static class BinaryTreeDemo
    {
        public Node root;
        public void setter(Node root)
        {
            this.root = root;
        }
        public void inOrder()
        {
            if (this.root == null)
            {
                System.out.println("空树");
            }else
            {
                this.root.inOrder();
            }
        }
        public void add(Node node)
        {
            if (root == null)
            {
               setter(node);
            }else
            {
                root.add(node);
            }
        }
    }
    static class Node
    {
        public Node left;
        public Node right;
        public int value;
        public Node(int value)
        {
            this.value = value;
        }

        @Override
        public String toString()
        {
            return "Node{" +
                    "value=" + value +
                    '}';
        }
        public void add(Node node)
        {
            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 inOrder()
        {
            if (this.left != null)
            {
                this.left.inOrder();
            }
            System.out.println(this);
            if(this.right != null)
            {
                this.right.inOrder();
            }
        }
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!