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
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.
The recursive method should call result.append(node) rather than result.append(node.left)
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.