//前序线索化二叉树 public void PreThreading(ThrTreeNode <T> root) { if (root == null) { return; } //左指针为空,将左指针指向前驱节点 if (root.lChild == null) { root.lChild = pre; root.Ltag = true; } //前一个节点的后继节点指向当前节点 if (pre != null && pre.rChild == null) { pre.rChild = root; pre.Rtag = true; } pre = root; //如果左指针不是索引,处理左子树 if (!root.Ltag) { PreThreading(root.lChild); } //如果右指针不是索引,处理右子树 if (!root.Rtag) { PreThreading(root.rChild); } }
//中序遍历线索二叉树,按照后继方式进行遍历 public void InOrderTraversal(ThrTreeNode <T> root) { //1、找中序遍历方式最开始的节点 while (root != null && !root.Ltag) { root = root.lChild; } while (root != null) { //Console.Write(root.Data + " "); if (!root.Data.Equals('#')) { resultthrin += root.Data; } //如果右指针是线索 if (root.Rtag) { root = root.rChild; } //如果右指针不是线索,找到右子树开始的节点(即右子树最左边的结点) else { root = root.rChild; while (root != null && !root.Ltag) { root = root.lChild; } } } }
//中序遍历线索化 // 如果当前结点无左孩子,则刚刚访问的pre结点为当前结点的前驱 // 如果刚刚访问的pre结点无右孩子,则当前结点为pre结点的后继 public void InTreading(ThrTreeNode <T> root) { if (root == null) { return; } //处理左子树 InTreading(root.lChild); //左指针为空,将左指针指向前驱节点 if (root.lChild == null) { root.lChild = pre; root.Ltag = true; } //前一个节点的后继节点指向当前节点 if (pre != null && pre.rChild == null) { pre.rChild = root; pre.Rtag = true; } pre = root; //处理右子树 InTreading(root.rChild); }
private void button1_Click(object sender, EventArgs e) { char[] data = (textBox1.Text.Trim()).ToCharArray(); //char[] data = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' }; BinaryTree <char> tree = new BinaryTree <char>(data); tree.leaves = 0; tree.PreTraversal(tree.Head); tree.InTraversal(tree.Head); tree.LastTraversal(tree.Head); ThrBinaryTree <char> tree1 = new ThrBinaryTree <char>(); ThrTreeNode <char> root = tree1.CreatBinaryTree(data, 0); //Console.WriteLine("二叉树中序线索化..."); tree1.InTreading(root); //Console.Write("中序按后继节点遍历线索二叉树结果:"); tree1.InOrderTraversal(root); //Console.WriteLine(); //Console.Write("中序按前驱节点遍历线索二叉树结果:"); //Console.WriteLine(); ThrTreeNode <char> root2 = tree1.CreatBinaryTree(data, 0); //Console.WriteLine("二叉树先序线索化..."); tree1.PreThreading(root2); //Console.Write("先序按后继节点遍历线索二叉树结果:"); tree1.PreInTraversal(root2); textBox2.Text = tree.resultpre; textBox3.Text = tree.resultin; textBox4.Text = tree.resultpost; }
//通过数组构建二叉树 public ThrTreeNode <T> CreatBinaryTree(T[] vals, int index) { ThrTreeNode <T> root = null; if (index < vals.Length) { root = new ThrTreeNode <T>(vals[index]); root.lChild = CreatBinaryTree(vals, index * 2 + 1); root.rChild = CreatBinaryTree(vals, index * 2 + 2); } return(root); }
//前序遍历线索二叉树(按照后继线索遍历) public void PreInTraversal(ThrTreeNode <T> root) { while (root != null) { while (!root.Ltag) { //Console.Write(root.Data + " "); if (!root.Data.Equals('#')) { resultthrpre += root.Data; } root = root.lChild; } //Console.Write(root.Data + " "); if (!root.Data.Equals('#')) { resultthrpre += root.Data; } root = root.rChild; } }
public ThrTreeNode(T val) { this.data = val; this.lChild = null; this.rChild = null; }