我正在研究构建二叉树并将其显示为作业分配的代码(因此,我必须从头开始构建树)。但是,我不能似乎找出了一种方法来防止节点从树上穿过4级。我希望有人能够帮助开始我的大脑......但是有没有办法检查树下面有多少层,并调整上面各层节点之间的水平距离?在我的研究中,我看到一些做法不同,但我必须通过displayTree()方法递归地按照赋值参数进行递归。任何帮助表示赞赏。在二叉树中交叉的节点
P.S.当前的horizontalGap变量是我一直在修补的东西,所以如果它与代码混淆,我很抱歉。这里是displayTree()方法。
//displayTree() with crossing issue
//**************************************************************************
public void displayTree(Graphics g, Node localTree, int x, int y, int level)
{
// Display the root
int verticalGap = 50;
int horizontalGap = 250/level;
g.drawOval(x, y, radius, radius);
g.drawString(localTree.getKey() + "", x + (radius/4) , y + 20);
if (localTree.getLeft() != null) {
// Draw a line to the left node
lineToLeftChild(g, x - horizontalGap, y + verticalGap, x, y);
// Draw the left subtree recursively
displayTree(g, localTree.leftChild, x - horizontalGap, y + verticalGap, level + 1);
}
if (localTree.rightChild != null) {
// Draw a line to the right node
lineToRightChild(g, x + horizontalGap, y + verticalGap, x, y);
// Draw the right subtree recursively
displayTree(g, localTree.rightChild, x + horizontalGap, y + verticalGap, level + 1);
}
}//end displayTree()
//**************************************************************************
//Line to child
//**************************************************************************
private void lineToLeftChild(Graphics g, int x1, int y1, int x2, int y2) {
g.drawLine(x1 + (radius/2), y1, x2, y2 + (radius/2));
}//end LinetoLeft
//**************************************************************************
//Line to child
//**************************************************************************
private void lineToRightChild(Graphics g, int x1, int y1, int x2, int y2) {
g.drawLine(x1 + (radius /2), y1, (x2 + radius) , y2 + (radius/2));
}//end line to Right()
//**************************************************************************
}