简体   繁体   English

树结构没有正确打印出来

[英]Tree Structure Not Correctly Printing Out

I am having trouble with a basic binary search tree that I have created in Java.我在使用 Java 创建的基本二叉搜索树时遇到了问题。 I am trying to output the tree structure in the console with prepended spaces before a nodes value with respect to how deep the node is.我试图在控制台中输出树结构,并在节点值之前添加与节点深度有关的前置空格。

For some reason my printTree() function is outputting a tree structure that seems slightly backwards.出于某种原因,我的printTree()函数正在输出一个看起来有点倒退的树结构。 I wouldn't think that (5 0.0) would be indented because it would stay as the root in a basic tree like this.我不认为(5 0.0)会缩进,因为它会作为这样的基本树的根。

Below is my function and the output:下面是我的函数和输出:

Note : c creates the root, s adds a key and value, and xp outputs the tree.注意c创建根, s添加键和值, xp输出树。

private int k;
private float d;
private Node left, right;

public Node(int k) {
    this.k = k;
}

public Node(int k, float d) {
    this.k = k;
    this.d = d;
}

private int height(Node n) {
    if (n == null)
        return -1;
    return 1 + Math.max(height(n.left), height(n.right));
}

private void printTree(Node n) {
    if (n == null)
        return;
    System.out.println(new String(new char[3 * height(n)]).replace("\0", " ") + "(" + n.k + " " + n.d + ") ");
    printTree(n.left);
    printTree(n.right);
}

Output:输出:

在此处输入图片说明

I'm pretty sure that based on my input that 5 should not be indented at all because it would be root node.我很确定根据我的输入, 5 根本不应该缩进,因为它是根节点。

I believe that it should look something like (based on a binary search tree):我相信它应该看起来像(基于二叉搜索树):

(5 0.0)
    (4 1.2)
        (2 3.5)
    (6 7.5)
        (87 96.5)

(with the correct amount of prepended spaces of course) (当然有正确数量的前置空格)

Can anybody explain what I'm doing wrong?谁能解释我做错了什么?

You calculate the number of spaces as 3*height(n) .您将空格数计算为3*height(n) height(n) calculates the maximum path length of the left and the right tree, so the root will always be the furthest to the right. height(n)计算左树和右树的最大路径长度,所以根总是最右边的。

either calculate the height of a node as the length of the path from the node to the root or precalculate the maximum height and set the number of whitespaces for a node to maxHeight - height(n) .要么将节点的高度计算为从节点到根的路径长度,要么预先计算最大高度并将节点的空格数设置为maxHeight - height(n)

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

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