We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,610 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Algorith for complete binary tree

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;
	}
3
Contributors
3
Replies
2 Hours
Discussion Span
1 Year Ago
Last Updated
6
Views
ilovejava
Junior Poster in Training
77 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
Skill Endorsements: 0

Post error code you receive when code crashes

hbluthi
Light Poster
38 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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

ilovejava
Junior Poster in Training
77 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
Skill Endorsements: 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.

ztini
Posting Whiz in Training
299 posts since Jan 2011
Reputation Points: 51
Solved Threads: 53
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0954 seconds using 2.79MB