简体   繁体   中英

How memory-efficient is Binary Tree implementation in Java?

So I just wrote code for insertion of nodes in binary tree (NOT BST).

I noticed that every time the recursive insert returns a 'node', it is assigned to the initial node.

Does this mean, that the memory reference of root of this tree would change on the completion of each insert?

public  void add(int data)
{
    root=add(root,data);
}

public static BinaryNode add(BinaryNode node, int data) {


    if(node==null)
    {
        node=new BinaryNode(data);

    }
    else {
        ///IF not 1st element, flow enters this part
        if(node.left==null && node.right==null)
        {
            node.left=add(node.right,data);
        }
        else if (node.right == null) {
            node.right=add(node.right, data);

        } else {
            node.left=add(node.left, data);

        } 
    }
    return node;
}

Within add the only time you change node is if the tree at that point is empty, so the answer is no except for the first insert.

However, note that you add a new level to the tree only on the left (first if condition) so the "tree" you build is highly unbalanced to the left. This isn't really a "tree", it's more like a strange linked list. Also, since you don't maintain any particular sequence it can't be better than a simple unordered list for searches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM