'此代码目的是用Treeview显示满二叉树 '用for循环从上到下从左到右依次填充 '开发环境:.net '新手学习,请多指教! 'QQ 675686066 'email leiyang-ge@163.com Public Class Form1 Private Const Max = 100 '把二叉树的节点放到数组中,Lchild,Rchild分别指向孩子所在下标 Public Structure Node Public Num As Integer Public Lchild As Integer Public Rchild As Integer End Structure '新添节点的父节点可以看做一个队列 Dim Head As Integer '头 Dim Tail As Integer '尾 Dim Nodes(Max) As Node Dim TreeNodes(Max) As TreeNode '用-1作为终止,相当于c语言的NULL Private Sub InitNodes() For I As Integer = 0 To Max - 1 Nodes(I).Num = -1 Nodes(I).Lchild = -1 Nodes(I).Rchild = -1 Next End Sub ''' <summary> ''' 添加节点 ''' </summary> ''' <param name="Num">新节点的父节点的下标</param> ''' <remarks></remarks> Private Sub AddNode(ByVal Num As Integer) Dim NewNode As Node NewNode.Num = Num NewNode.Lchild = -1 NewNode.Rchild = -1 If Nodes(Head).Lchild = -1 Then '添加内存中节点 Tail += 1 Nodes(Tail) = NewNode Nodes(Head).Lchild = Tail '添加树节点 TreeNodes(Tail) = New TreeNode(Num.ToString) TreeNodes(Head).Nodes.Add(TreeNodes(Tail)) ElseIf Nodes(Head).Rchild = -1 Then Tail += 1 Nodes(Tail) = NewNode TreeNodes(Tail) = New TreeNode(Num.ToString) TreeNodes(Head).Nodes.Add(TreeNodes(Tail)) Nodes(Head).Rchild = Tail Head += 1 End If End Sub '递归输出 Private Sub PrintTree(ByVal Root As Integer) If Root = -1 Then Return End If If Nodes(Root).Num <> -1 Then MsgBox(Nodes(Root).Num) End If PrintTree(Nodes(Root).Lchild) PrintTree(Nodes(Root).Rchild) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click InitNodes() Nodes(1).Num = 1 Head = 1 Tail = 1 TreeNodes(1) = New TreeNode("1") TreeView1.Nodes.Add(TreeNodes(1)) For I As Integer = 2 To 30 AddNode(I) Next TreeView1.ExpandAll() '递归输出 'PrintTree(1) End Sub End Class