using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace SysPermission { public partial class Form1 : Form { public Form1() { InitializeComponent(); } #region 二叉树 void MidOrder<T>(nodes<T> rootNode) { if (rootNode != null) { MidOrder<T>(rootNode.LNode); MessageBox.Show(rootNode.Data.ToString()); MidOrder<T>(rootNode.RNode); } } void PreOrder<T>(nodes<T> rootNode) { if (rootNode != null) { MessageBox.Show(rootNode.Data.ToString()); PreOrder<T>(rootNode.LNode); PreOrder<T>(rootNode.RNode); } } nodes<string> BinTree() { nodes<string>[] binTree = new nodes<string>[8]; //创建结点 binTree[0] = new nodes<string>("A"); binTree[1] = new nodes<string>("B"); binTree[2] = new nodes<string>("C"); binTree[3] = new nodes<string>("D"); binTree[4] = new nodes<string>("E"); binTree[5] = new nodes<string>("F"); binTree[6] = new nodes<string>("G"); binTree[7] = new nodes<string>("H"); //使用层次遍历二叉树的思想,构造一个已知的二叉树 binTree[0].LNode = binTree[1]; binTree[0].RNode = binTree[2]; binTree[1].RNode = binTree[3]; binTree[1].LNode = binTree[4]; binTree[2].RNode = binTree[5]; binTree[2].LNode = binTree[6]; binTree[3].RNode = binTree[7]; //返回二叉树的根结点 return binTree[0]; } void AfterOrder<T>(nodes<T> rootNode) { if (rootNode != null) { AfterOrder<T>(rootNode.LNode); AfterOrder<T>(rootNode.RNode); Console.WriteLine(rootNode.Data); } } void LayerOrder<T>(nodes<T> rootNode) { nodes<T>[] Nodes = new nodes<T>[20]; int front = -1; int rear = -1; if (rootNode != null) { rear++; Nodes[rear] = rootNode; } while (front != rear) { front++; rootNode = Nodes[front]; Console.WriteLine(rootNode.Data); if (rootNode.LNode != null) { rear++; Nodes[rear] = rootNode.LNode; } if (rootNode.RNode != null) { rear++; Nodes[rear] = rootNode.RNode; } } } #endregion nodes<string>[] nodeString = new nodes<string>[1000]; private void button1_Click(object sender, EventArgs e) { nodes<string> rootNode = BinTree(); PreOrder<string>(rootNode); } } class nodes<T> { T data; nodes<T> Lnode, Rnode, Pnode; public T Data { set { data = value; } get { return data; } } public nodes<T> LNode { set { Lnode = value; } get { return Lnode; } } public nodes<T> RNode { set { Rnode = value; } get { return Rnode; } } public nodes<T> PNode { set { Pnode = value; } get { return Pnode; } } public nodes() { } public nodes(T data) { this.data = data; } } }
二叉树
最新推荐文章于 2024-01-12 09:21:58 发布