我一直在尝试从 Node 切换到 Java,我想知道的一件事是如何以与 Node 显示方式类似的格式打印二叉树等对象。比如我的二叉树初始化代码如下:
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;
}
}
在 Node 中,该二叉树将显示如下:
TreeNode {
val: 1,
right: TreeNode { val: 3, right: null, left: null },
left:
TreeNode {
val: 2,
right: TreeNode { val: 4, right: null, left: null },
left: null } }
但是在Java中,当我这样做时 System.out.println(树);
输出 -> BinaryTree@4554617c
打印二叉树的正确方法是什么以及执行此操作的好方法是什么?有没有办法以 JSON 格式打印树?
最佳答案
打印tree
将为您提供主树 Node 的内存地址。如果要打印树的内容,则需要实现递归打印方法并递归树中的每个 Node 。
如果该 Node 是最终 Node (没有右树或左树),则打印该 Node 的内容。否则就从树上移下来。
您可以在沿着树向下或返回时打印,具体取决于您希望树的外观。
我希望我正确理解了这个问题。
关于java - 如何打印二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077997/