[binary search tree Java] improves toString and generatetree

Posted by monkeyj on Thu, 13 Feb 2020 21:24:02 +0100

Before the text

Yesterday, I played again.. So I'm sorry.. Improve the next binary search tree this morning... Red and black trees make my brain crack!!!


    public String toString() {
        System.out.println("Output tree: ");
        Queue<node> queue = new LinkedList<>();
        String out = "";
        int x=-10000;
        while (!queue.isEmpty()) {
            node s = queue.poll();
            if (s.getKey()<x) {
                out += "\n";
            out += (s.getKey() + " ");
            if (s.leftChild != null)
            if (s.rightChild != null)
        return out;

The method of sequence traversal is adopted, and then because the sequence traversal strictly follows the principle of layer by layer output, it is very simple to determine the layering condition that the current node is smaller than the previous node, so it must be layering. After all, in the same layer, from left to right, it must increase one by one, which is determined by the nature of binary search tree..

    public static void insertToTree(Tree tree,int x){
        System.out.println("\nInsert into the Tree : "+x+"\n");
        node newnode = new node(x);
        node tmp = tree.getRoot();
        if ( tmp==null)
            tree.root = newnode;
        while(tmp!=null) {
            if (x < tmp.getKey()) {
                if (tmp.leftChild==null) {
                    newnode.parent = tmp;
                    newnode.leftChild = null;
                    tmp.leftChild = newnode;
                    tmp = tmp.leftChild;
            else {
                if ( tmp.rightChild==null) {
                    newnode.parent = tmp;
                    newnode.rightChild =null;
                    tmp.rightChild = newnode;
                    tmp = tmp.rightChild;

    public static Tree generateTree(int[] arr){
        Tree tree = new Tree();
        for (int i=0;i<arr.length;++i) {
            if (i!=arr.length/2) {
        return tree;

Well, I'm a fool ahead... Actually, I want to insert it in the middle of the tree instead of directly becoming a leaf node.. I am a fool..

So it perfectly unifies the generation and insertion, but isn't the spanning tree the result of multiple inserts?

After the text

Eat through the red and black trees today! No explanation!! Then watch the video again and check the collection, and find that the charm of data structure is really big!!!