Mickey
Mickey

Reputation: 127

Tree printing extra characters

    public class TreeWords {

    public static void main (String[] args){
        Tree tree = new Tree();
        System.out.println("Enter your string.");
        Scanner in = new Scanner(System.in);
        String input = in.next();

        for (char ch : input.toCharArray()) {
            Tree tmp = new Tree(ch);
            tree.insert(tree, tmp);
        }
        tree.printInOrder(tree);
    }
}

class Tree {

    //Tree variables
    char letter;
    Tree left, right;


    //Constructors
    public Tree(){
        left = right = null;
    }
    public Tree(char input) {
        left = right = null;
        letter = input;
    }

    //Methods
    public void printInOrder(Tree root) {
        if (root == null) return;
        printInOrder(root.left);
        System.out.print(root.letter);
        printInOrder(root.right);
    }

    public void insert(Tree root, Tree tmp) {
        if (root == null) {
            root = tmp;
            return;
        }
        if (root.left == null) {
            root.left = tmp;
            return;
        }
        if (root.right == null) {
            root.right = tmp;
            return;
        }
        insert(root.left, tmp);
        insert(root.right, tmp);
    }
}

This is my sample code for a small program that I'm working on. Basically, it is supposed to add a character to each tree node. But somehow, there seems to be either printing extra characters, or adding extra characters. For example:

Input : aaa
Output : aaaa

Input : hello
Output : oloholo�oloeolo

Upvotes: 0

Views: 169

Answers (1)

Burleigh Bear
Burleigh Bear

Reputation: 3314

There's a couple of problems here. These two will hopefully get you started

The first is that parameters in Java are pass-by-value, so assigning a value to them will not be visible outside the method. So the first four lines of 'insert' do nothing.

The second is that once a node is 'full' (i.e. both left and right are non-null) you are inserting the next value into both the left and right sub-trees.

It's also possible that you're missing a '<' comparison in the insert method too, but I'm not sure if 'printInOrder' is referring to insert order or lexicographic order.

Upvotes: 1

Related Questions