• Post Reply Bookmark Topic Watch Topic
  • New Topic

Binary tree from scratch: resursive scope?  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey all,

My instructor is having us implement an AVL tree in Java, without using any of the predefined AVL classes. Right now i'm working on the basics of the program (Insert, and Print inorder.) Both of those functions i have implemented in the "BinaryNode" class. Something isnt working when I go to print them out, i'm not sure if it is finding leaf nodes or overwriting existing ones. And when it prints, it only prints out one value. Is there something going on with the scope of the Node objects when I use recursive calls? Here is the code for AVLTree class and BinaryNode class:





Thanks everyone!!
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That Insert method will never add a child to a new node. The first branch of the outer "if" is followed, since both children start out as null. Then inside that if, either the argument is discarded, or the node's value is set to the argument. No children will ever be created! You need to rethink that logic.
 
Justin Swartsel
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, so I moved the insert function over to the main AVLTree class and changed it to:




and I made a "BinaryNode root" in the body of the AVLTree class, so it is a global object. But It is still only inserting the root, and exactly one left and right child. For some reason It will only overwrite the existing children and not create new ones? I am having a lot of trouble figuring this out.

Justin
 
Justin Swartsel
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahhh Bingo! I got it. I was overwriting each child by using new BinaryNode(). Instead I put an if statement, initializing the child only if it was null.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!