如何打印二叉树

时间:2018-04-28 15:14:44

标签: java json node.js binary-tree println

我一直在尝试从Node切换到Java,我想知道的一件事是如何以与节点如何显示它类似的格式打印二进制树之类的对象。例如,我的二叉树启动代码如下:

select tmp.country, tmp.maxvalue, tmp.id, users.sex from (
select users.country as country, max(transactions.value) as maxvalue, max(users.id) as id 
from users
inner join transactions on users.id = transactions.id
group by users.country) tmp
inner join users on tmp.id = users.id;

在节点中,此二叉树将显示如下:

public class BinaryTree {
    int data;
    BinaryTree left, right;

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree(1);
        tree= new BinaryTree(1);
        tree.left = new BinaryTree(2);
        tree.right= new BinaryTree(3);
        tree.left.right = new BinaryTree(4);
        System.out.println(tree); // output -> BinaryTree@4554617c
    }

    public BinaryTree(int data) {
      super();
      int val;
      this.left = this.right = null;
  }
}

然而在Java中,当我这样做时 的System.out.println(树);

输出 - >二叉树@ 4554617c

打印BinaryTree的正确方法是什么?有什么好方法可以做到这一点?有没有办法以JSON格式打印树?

2 个答案:

答案 0 :(得分:1)

打印tree将为您提供主树节点的内存地址。如果要打印树的内容,则需要实现递归打印方法并递归树中的每个节点。
如果节点是最终节点(没有右侧或左侧树),则打印该节点的内容。否则向下移动树。 您可以在树下或返回的路上打印,具体取决于您希望树的外观 我希望我能正确理解这个问题。

答案 1 :(得分:1)

我在堆栈溢出时找到了this解决方案并对其进行了修改......

public static class TreeNode
{
    int value;
    TreeNode leftChildren;
    TreeNode rightChildren;

    public TreeNode(int value, TreeNode left, TreeNode right)
    {
        this.value = value;
        this.leftChildren = left;
        this.rightChildren = right;
    }

    public addLeftNode(TreeNode node)
    {
        this.leftChildren = node;
    }

    public addRightNode(TreeNode node)
    {
        this.rightChildren = node;
    }

    public void print(String prefix)
    {
        print(prefix, true);
    }

    private void print(String prefix, boolean isTail)
    {
        System.out.println(prefix + (isTail ? "└── " : "├── ") + this.toString());

        if(null != leftChildren)
        {
            leftChildren.print(prefix + (isTail ? "    " : "│   "), (null == rightChildren ? true : false));
        }

        if(null != rightChildren)
        {
            rightChildren.print(prefix + (isTail ?"    " : "│   "), true);
        }

    }

    @Override public String toString()
    {
        return "TreeNode { Value: " + this.value + "}";
    }
}

第一个节点表示左侧,第二个节点表示二叉树中的右侧节点。

编辑:您可以像这样使用:

TreeNode root = new TreeNode(22, null, null);

root.addLeftNode(new TreeNode(15, null, null));
root.addRightNode(new TreeNode(35, new TreeNode(27, null, null), null));

root.print(); // This will print recursively all sub-nodes

替代你可以写一个这样的包装类:

public class BinaryTree
{
    private TreeNode root;

    // implementation of getters and setters

    public void print()
    {
        this.root.print();
    }
}
相关问题