简体   繁体   English

AVL树toString()的实现

[英]implementation of AVL tree toString()

This is my toString() but it doesn't work properly 这是我的toString()但它无法正常工作

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} 这是打印出来的方法:{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. 此外, TreeNode没有覆盖toString()方法,因此它显示了哈希码。

  1. The recursive method should call result.append(node) rather than result.append(node.left) 递归方法应该调用result.append(node)而不是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" 您的TreeNode类应该覆盖toString(显示一些节点ID),否则您将看到默认的toString(来自Object),它看起来像“AbstractTreeMap $ TreeNode @ 15a8767”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM