kaboom
kaboom

Reputation: 833

implementation of AVL tree toString()

This is my toString() but it doesn't work properly

public String toString() {
        StringBuilder str = new StringBuilder("{");
        traverse(root, str);
        str.append("}");

        return str.toString();
    }

    private void traverse(TreeNode node, StringBuilder str){
        if (node == null){
            return;
        }

        if (node.left != null) {
            traverse(node.left, str);
            str.append(", ");
        }

        str.append(node.left);

        if (node.right != null) {
            str.append(", ");
            traverse(node.right, str);
        }
    }

this is what the method print out: {null, AbstractTreeMap$TreeNode@15a8767}

any help is appreciated. thank you

Upvotes: 0

Views: 1068

Answers (2)

Narendra Pathai
Narendra Pathai

Reputation: 41955

if (node.left != null) {
      inOrder(node.left, result);
      result.append(", ");
}

result.append(node.left); //should not be node.left

do this instead

if (node.left != null) {
     inOrder(node.left, result);
     result.append(", ");
}

result.append(node); //this will print the node itself

Also TreeNode does not have toString() method overridden so it shows the hash code.

Upvotes: 2

Eyal Schneider
Eyal Schneider

Reputation: 22446

  1. The recursive method should call result.append(node) rather than result.append(node.left)

  2. Your TreeNode class should override toString (displaying some node id), otherwise you'll see the default toString (from Object), which looks like "AbstractTreeMap$TreeNode@15a8767"

Upvotes: 0

Related Questions