我正在尝试从字符串中解析多树。
语法:
根(树,树,树 ...)=
例如 :
1(2,3,4(5,3),4(7,8,5)) =
我想出了如何从字符串中解析二叉树:
我的代码:
Public Class Tree
Public l As Tree = Nothing
Public r As Tree = Nothing
Public value As String
Public Sub New(ByVal Str As String)
If Str = "" Then Throw New Exception("Input String is Nothing ("""")")
Dim Error_Report As String = RunCheck(Str)
If Not Error_Report = "" Then Throw New Exception(Error_Report)
If Str.Contains("(") Then
Try
value = Str.Substring(0, Str.IndexOf("("))
BulidTreeByInTo(Str.Substring(Str.IndexOf("(") + 1, Str.Length - 2 - Str.IndexOf("(")), l, r)
Catch ex As Exception
Throw ex
End Try
Else
value = Str
End If
End Sub
Private Function RunCheck(ByVal str As String) As String
Dim Open_Close As Integer = 0
For i = 0 To str.Length - 1 Step 1
If str(i).ToString = "(" Then
Open_Close += 1
ElseIf str(i).ToString = ")" Then
Open_Close -= 1
End If
If i >= 1 Then
If (str(i - 1).ToString = ")" And str(i).ToString = "(") Or (str(i - 1).ToString = "(" And str(i).ToString = ")") Then
Return "Error in bracket At Index " & i
End If
If (str(i - 1).ToString = "(" And str(i).ToString = ",") Or (str(i - 1).ToString = "," And str(i).ToString = ")") Or (str(i - 1).ToString = "," And str(i).ToString = "(") Or (str(i - 1).ToString = "," And str(i).ToString = ",") Then
Return "Error in Comma At Index " & i
End If
End If
Next
If Not Open_Close = 0 Then Return "Not all existing brackets are Closed"
Return ""
End Function
Private Function GetTheSameLevel(ByVal s As String) As Integer
Dim level As Integer = 0
For i = 0 To s.Length - 1 Step 1
If s(i).ToString = "," And level = 0 Then
Return i
End If
If s(i).ToString = "(" Then
level += 1
End If
If s(i).ToString = ")" Then
level -= 1
End If
Next
Return -1
End Function
Private Sub BulidTreeByInTo(ByVal str As String, ByRef l1 As Tree, ByRef r1 As Tree)
Dim MiddleIndex As Integer = GetTheSameLevel(str)
Dim p1 As String = str.Substring(0, MiddleIndex)
Dim p2 As String = str.Substring(MiddleIndex + 1, str.Length - 1 - MiddleIndex)
Try
If p1.Contains("(") Then
If Not p1.Substring(0, p1.IndexOf("(")).ToString = "\" Then
l1 = New Tree(p1.Substring(0, p1.IndexOf("(")))
BulidTreeByInTo(p1.Substring(p1.IndexOf("(") + 1, p1.Length - 2 - p1.IndexOf("(")), l1.l, l1.r)
End If
Else
If Not p1 = "\" Then
l1 = New Tree(p1)
End If
End If
If p2.Contains("(") Then
If Not p2.Substring(0, p2.IndexOf("(")).ToString = "\" Then
r1 = New Tree(p2.Substring(0, p2.IndexOf("(")))
BulidTreeByInTo(p2.Substring(p2.IndexOf("(") + 1, p2.Length - 2 - p2.IndexOf("(")), r1.l, r1.r)
End If
Else
If Not p2 = "\" Then
r1 = New Tree(p2)
End If
End If
Catch ex As Exception
Throw ex
End Try
End Sub
End Class