2 Replies - 9502 Views - Last Post: 13 December 2011 - 10:33 PM Rate Topic: -----

#1 EndlessIter   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-December 11

Infinite loop when inserting into a binary search tree

Posted 13 December 2011 - 06:35 PM

Hello, when I run my code I get an infinite loop. I am using a binary search tree. When I run the debugger I realized that the find() contains the loop. When I create a new node.left or node.right it creates an infinite amount of pointers to a left or right node. I have been stuck on this same problem for 3 days, any help would be awesome. I have tried rewriting it 2 other ways, drawing it out on paper and debugging it many many times.

public void insertId(String id)
	 {
	       String converted_id = id.toLowerCase();
		    Id new_node;
		
		if (find(converted_id))
		   return;
	   else
		{
		   new_node = new Id(converted_id);
			if (parent == null)
			   root = new_node;
		   else if (converted_id.compareTo(parent.key) < 0)
			   parent.left = new_node;
			else
			   parent.right = new_node;[/where the assignment that creates a loop happens, for my .txt file]
		}
        }
/////////////////////////////////////////////

         public boolean find(String data)
	 {
	    Id node = root;
		 boolean found = false;
		 parent = null;
		 
		 while (!found && node != null)
		 {
		    parent = node;
			 if (data.compareTo(node.key) < 0)
			    node = node.left;
		    else if (data.compareTo(node.key) > 0)
			    node = node.right;
			 else
			 {
			    found = true;
				 //node.id_list.insertAfter(data.toLowerCase());
				 return found;
			 }
		 }
		 return found;
	 }


I wish I could have showed this in a nicely formatted layout, but this site would not conform to my spacing.

Edited by macosxnerd101: Please use code tags, like so: :code:.

Is This A Good Question/Topic? 0
  • +

Replies To: Infinite loop when inserting into a binary search tree

#2 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 12350
  • View blog
  • Posts: 20,984
  • Joined: 19-March 11

Re: Infinite loop when inserting into a binary search tree

Posted 13 December 2011 - 08:49 PM

I hate to ask obvious questions, but are you sure that you don't have cycles in your tree? For example, if root or any other node points to itself, you could get this loop.
Was This Post Helpful? 0
  • +
  • -

#3 EndlessIter   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-December 11

Re: Infinite loop when inserting into a binary search tree

Posted 13 December 2011 - 10:33 PM

I am not sure why this worked, but all I did to fix this issue is use a mutator method to set the left and right nodes, instead of changing them directly...

Thank you all who read this and tried to help.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1