我正在研究構建二叉樹並將其顯示爲作業分配的代碼(因此,我必須從頭開始構建樹)。但是,我不能似乎找出了一種方法來防止節點從樹上穿過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()
//**************************************************************************
}