資料檔第1列 一個數字 n ,代表 n 組資料,接著每組資料二列
每組的第1列一個數字x,每組第2列 x 個數字以逗號隔開
將讀入的 x 數字建成二元搜尋樹,然後依二元樹的後序拜訪 印出
參考程式碼:
Dim dt(20) As Integer '資料
Dim chi(20, 1) As Integer '左、右子樹
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileOpen(1, "in1.txt", OpenMode.Input)
' FileOpen(2, "in2.txt", OpenMode.Input) '本題只一 in1
FileOpen(3, "out.txt", OpenMode.Output)
For fn = 1 To 1 '本題只一 in1
If fn > 1 Then PrintLine(3) '本題只一檔,若2檔,中間空一列
Dim n As Short = LineInput(fn) '每組第一列 N 組資料
Do Until n = 0
n -= 1
Dim x As Short = LineInput(fn) ' x 個節點
For i = 0 To x - 1
chi(i, 0) = -1 : chi(i, 1) = -1
Next
Dim id() = LineInput(fn).Split(",")
dt(0) = id(0)
For i = 1 To x - 1
dt(i) = id(i)
gbst(i, dt(i))
Next
' For j = 0 To x - 1 '此段多印的 左樹、資料、右樹
' PrintLine(3, j & " " & chi(j, 0) & ":" & dt(j) & ":" & chi(j, 1))
' Next
po_t(chi(0, 0))
po_t(chi(0, 1))
PrintLine(3, dt(0) & "")
Loop
Next ' fn
End
End Sub
Sub gbst(ByVal i, ByVal v) '建二元搜尋樹
Dim p As Integer = 0
Dim dir As Integer '0往左 或 1往右
Do Until p = -1
Dim pp As Integer = p
If v < dt(p) Then '往左
dir = 0
p = chi(p, 0)
Else '往右
dir = 1
p = chi(p, 1)
End If
If p = -1 Then
chi(pp, dir) = i
Return
End If
Loop
End Sub
Sub po_t(ByVal p As Integer) '後序列印
If p = -1 Then Return
po_t(chi(p, 0))
po_t(chi(p, 1))
Print(3, dt(p) & ",")
End Sub
/*範例輸入in1.txt
4
8
7,4,1,5,12,8,9,15
10
9,4,1,5,12,11,10,15,2,3
9
4,1,5,12,11,10,15,2,3
4
1,2,3,4
範例輸出out.txt
1,5,4,9,8,15,12,7
3,2,1,5,4,10,11,15,12,9
3,2,1,10,11,15,12,5,4
4,3,2,1
*/
0 意見:
張貼留言