Luchnik
Luchnik

Reputation: 1087

Binary Tree in Java. Problems with System.out.println()

I have to make an expression tree. This is a single example model of it. But It shows me strange chars but not my strings. Can you help me solve this problem. And another one question: can you show me the way to simplify my code. What about this part of code? Can I do without it?

public Iterator<TreeNode<T>> iterator() {
    return null;
}

enter image description here

import java.util.*;

public class TreeNode<T> implements Iterable<TreeNode<T>> {
    T data;
    TreeNode<T> parent;
    List<TreeNode<T>> children;

    public TreeNode(T data) {
        this.data = data;
        this.children = new LinkedList<TreeNode<T>>();
    }

    public TreeNode<T> addChild(T child) {
        TreeNode<T> childNode = new TreeNode<T>(child);
        childNode.parent = this;
        this.children.add(childNode);
        return childNode;
    }

    public Iterator<TreeNode<T>> iterator() {
        return null;
    }

    public static void main(String[] args){
        TreeNode<String> root = new TreeNode<String>("root");

        System.out.println("                          " + root + "                         ");
        System.out.println("                         /               \\          ");

        TreeNode<String> node1 = root.addChild("node1");
        TreeNode<String> node2 = root.addChild("node2");
        System.out.println("               " + node1 + "      " + node2);

        System.out.println("                                            \\");
        TreeNode<String> node20 = node2.addChild(null);
        System.out.println("                                        " + node20);
        System.out.println("                                            / \\");

        TreeNode<String> node21 = node2.addChild("node21");
        TreeNode<String> node210 = node20.addChild("node210");
        System.out.println("                             " + node21 + "   " + node210);             
    }
}

Upvotes: 0

Views: 128

Answers (2)

b4hand
b4hand

Reputation: 9770

You need to override the toString method on TreeNode. Also if you don't want to implement the iterator method then you should not implement Iterable.

Upvotes: 2

codebox
codebox

Reputation: 20254

To see more meaningful values in your output you should override the toString() method of TreeNode, maybe something like:

@Override
public String toString(){
    return String.valueOf(this.data);
}

Upvotes: 5

Related Questions