1.11M Members

Algorith for complete binary tree

 
0
 

This is my code for adding and removing from a binary tree but apparently its not complete can anyone tell me what to do to make it complete tree?

public void add(IBinaryTreeNode<E> e) {
		
		if (getRoot() == null) {
			setRoot(e);
		} else {
			//SAME HERE
			IBinaryTreeNode<E> node = getLastNode();
			node.setRightChild(e);
			e.setParent(node);
		}
		setLastNode(e);
		setSize(getSize() + 1);
	}
	@Override
	public IBinaryTreeNode<E> remove() {
		
		IBinaryTreeNode<E> node = getLastNode();
		if (!node.equals(getRoot())) {
			//IM SURE SOMETHING WRONG HERE
			node.getParent().setRightChild(null);
			setLastNode(node.getParent());
		} else {
			setLastNode(null);
			setRoot(null);
		}
		node.setParent(null);
		setSize(getSize() - 1);
		return node;
	}
 
-2
 

Post error code you receive when code crashes

 
0
 

I do not receive any errors but my tree is shifting to the right i want to figure out way to make it a complete binary tree

 
0
 

//IM SURE SOMETHING WRONG HERE

Yes.

Consider this tree:

root
         /     \
    node1       node2
    /   \        /   \
node3  node4  node5  node6

Using your code, if I remove node1 this is what happens:

I get root and I set root's right to null (what?). Then I set the node's parent to null. However, root still has a left reference to the deleted node (that's not right either).

How are you ordering your nodes and balancing your tree? This is important as it determines whether node4 should take node1's spot, or whether node3 should take node1's spot, or whether the root should take node1's spot.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: