我在使用Java创建的基本二进制搜索树时遇到问题。我试图在控制台中使用前置空格输出树结构,节点值与节点的深度相关。
出于某种原因,我的printTree()
函数正在输出看似略微向后的树结构。我不认为(5 0.0)
会缩进,因为它会像这样在基本树中保留根。
以下是我的功能和输出:
注意: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);
}
输出:
我很确定根据我的输入,5根本不应缩进,因为它将是根节点。
我认为它应该看起来像(基于二叉搜索树):
(5 0.0)
(4 1.2)
(2 3.5)
(6 7.5)
(87 96.5)
(当然有正确数量的前置空格)
有人可以解释我做错了吗?
答案 0 :(得分:1)
您将空格数计算为Option Explicit
Sub MakePointOnPlane()
Dim partDoc As PartDocument
Dim oSel
Dim status
Dim myPart As Part
Dim HSF As HybridShapeFactory
Set partDoc = CATIA.ActiveDocument
Set oSel = partDoc.Selection
Set myPart = partDoc.Part
Set HSF = myPart.HybridShapeFactory
Dim point_ref
Dim line_ref
Dim Point As Reference
Dim Line As Reference
'Variables to pick point and edge
Dim iot1(0)
iot1(0) = "Vertex"
Dim iot2(0)
iot2(0) = "TriDimFeatEdge"
status = oSel.SelectElement2(iot1, "Select a vertex", False)
MsgBox oSel.Item(1).Type
Set point_ref = oSel.Item(1).Value
oSel.Clear
status = oSel.SelectElement2(iot2, "Select a line", False)
MsgBox oSel.Item(1).Type
Set line_ref = oSel.Item(1).Value
oSel.Clear
' Passing selected point and line to create a new plane. ' The plane is created using method normal to curve.
Dim hybridShapePlaneNormal1 As HybridShapePlaneNormal
Set hybridShapePlaneNormal1 = HSF.AddNewPlaneNormal(line_ref, point_ref)
Dim body1 As Body
Set body1 = myPart.Bodies.GetItem("PartBody")
Dim myPlane As Variant
Set myPlane = hybridShapePlaneNormal1
body1.InsertHybridShape hybridShapePlaneNormal1
myPart.InWorkObject = hybridShapePlaneNormal1
myPart.Update
End Sub
。 3*height(n)
计算左侧树和右侧树的最大路径长度,因此根将始终位于最右侧。
计算节点的高度,作为从节点到根的路径长度,或者预先计算最大高度,并将节点的空白数设置为height(n)
。