Reputation: 267
I have created a binary search tree class. I created my insertion method, height method, and print method. When I insert, everything looks fine. IF the root is null, I create a new root and set the item. But when I call my height method, it prints out 2 instead of 1. When I call my print method, it prints out all the elements including root twice. For example, I inserted the following elements in the following order: 9, 5, 4, 55, 555
When I call my PREorderPRINT method, it prints out: 9, 5, 4, 9, 55, 555
The values printed are correct except for the duplicate 9 in the middle which I never inserted. My insert method does NOT use recursion. But my height and print methods use recursion.
My recursive preOrderPrint checks if root!=null, then it prints item, gets left, and gets right. When I call preorder in my public preorder method, I first check it tree is empty, if not, then I print it by passing in root to preOrderPRint(root)
My recursive height method checks if root is null and returns zero. If not, it gets height of left and right subtrees of root, compares them, and returns either left+1 or right+1. When I call my public height method, i check if root is null and return zero, else call recursive height passing in root.
When I insert one element, 9, into the tree, and call my height method, it prints out the height is 2. But my size method prints out the correct size, 1. There has to be something wrong with my recursive preorderPrint and height methods. I can't seem to figure out what I'm missing. Is there a special case I forgot to add?
EDIT: I posted code and deleted it. Fixed the problem. All I had to do was change an else to an else-if and add a condition to compare root with item being inserted. A silly mistake by me.
Upvotes: 0
Views: 395
Reputation: 267
My problem was in my insertion method. My first case checked to see if the root node was null. If it is null, it creates a node equal to the root and sets the item.
My second case compared my root and checked to see if item being inserted was less than root, if so, it "gets" the node to the left. After this, if the item being inserted is greater than the root, it "gets" the node to the right.
Next I had another if-else block that set the item to the left if item was less than root. After this, I only had an else statement that set the item to the node to the right regardless if it was already inserted in the root==null case.
To fix my problem, I had to change this else statement to an if-else statement and add a condition that checks to see if item being inserted is greater than root. This prevented the root from being inserted twice.
Upvotes: 2