I’ve got a BST AVL, in Java, that I need to prove is balanced by printing the last ten nodes. My hack-y solution was, knowing the number of nodes, to get the values from the last 10 nodes of an in-order traversal. It’s working not as intended. The records are stored with lastname keys (no duplicate records are kept) and a printout of each node’s size results in 0s.
My printout has mostly ‘Z’ names… as expected, and then it also contains the very first record (of 26000) printing out. I’m guessing (hoping) it’s an issue with how I’ve devised my printout, as opposed to a fault in the tree? Is there a more elegant way to print the last 10 nodes, that would not have the error I have now, or is it likely there is a flaw in my tree rotations?
InOrder traverse and output: (output accessed through a get function)
public void inOrder(Node x)
{
if (x == null)
return; //stops recursion when there is no Node
inOrder(x.left); //always traverse left first
inOrder(x.right); //traverse right
inOrderTraversalOutput += Integer.toString((size(x.left)) +
(size(x.right))) + "\n";
bstNodes++;
//total nodes - 17151
if (bstNodes > 17145)
lastnodes += x.val.toString() + "Node left size: " +
size(x.left) + "\n" + "Node right size: " + size(x.right) +
"\n" + "----------------------------------------------------\n";
}
//modified to print total number of nodes
public String getTraversal()
{
inOrderTraversalOutput += Integer.toString(bstNodes) + "\n";
return inOrderTraversalOutput;
}
put method: (called through a method that passes root node, key and value)
private Node put(Node x, Key key, Value val)
{
if (x == null)
{
return new Node(key, val, 0);
}
int cmp = key.compareTo(x.key);
if (cmp < 0)
{
x.left = put(x.left, key, val);
//AVL Balance
if ((size(x.left) - size(x.right)) >= 2)
{
if (x.key.compareTo(x.left.key) < 0)
{
x = rotateWithLeftsapling(x);
} else
{
x = doubleWithLeftsapling(x);
}
}
} else if (cmp > 0)
{
x.right = put(x.right, key, val);
//AVL Balance
if ((size(x.right) - size(x.left)) >= 2)
{
if (x.key.compareTo(x.right.key) > 0)
{
x = rotateWithRightsapling(x);
} else
{
x = doubleWithRightsapling(x);
}
}
} else
{
x.val = val;
}
x.N = size(x.left) + size(x.right);
return x;
}
It looks like you are doing a post order traversal. To do an in order all the ‘work’ should happen between the calls to inorder(left) and inorder(right). I think if you fix this then you will be OK.
As it is, you are actually doing the work the root node last so I would expect it to print out.