static void Main(string[] args) { var binarySortTree = new BinarySortTree(); var testSortArray = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 100, 99, 88 }; foreach (var item in testSortArray) { binarySortTree.Insert(item); } if (binarySortTree != null) { Console.WriteLine("前序遍历"); binarySortTree.PreOrderTraversal(); Console.WriteLine("中序遍历"); binarySortTree.InOrderTraversal(); Console.WriteLine("后序遍历"); binarySortTree.PostOrderTraversal(); } }
public class NoedSort { /// <summary> /// 值 /// </summary> public int Value { get; set; } /// <summary> /// 左跟 /// </summary> public NoedSort Left { get; set; } /// <summary> ///右跟 /// </summary> public NoedSort Right { get; set; } /// <summary> /// 父类树 /// </summary> public NoedSort ParentNode { get; set; } }
/// <summary> /// 二叉排序 /// </summary> public class BinarySortTree { private NoedSort node; /// <summary> /// 新增 /// </summary> /// <param name="Value"></param> public void Insert(int Value) { node = Insert(node, null, Value); } private NoedSort Insert(NoedSort node, NoedSort parentNode, int value) { if (node == null) { return new NoedSort() { Value = value, ParentNode = parentNode }; } if (node.Value > value) { node.Left = Insert(node.Left, node, value); } else { node.Right = Insert(node.Right, node, value); } return node; } /// <summary> /// 前序遍历 /// </summary> public void PreOrderTraversal() { PreOrderTraversal(node); } /// <summary> /// 前序遍历 /// </summary> /// <param name="node"></param> private void PreOrderTraversal(NoedSort node) { if (node == null) { return; } Console.WriteLine(node.Value); // 访问根节点 PreOrderTraversal(node.Left); // 遍历左子树 PreOrderTraversal(node.Right); // 遍历右子树 } /// <summary> /// 中序遍历 /// </summary> public void InOrderTraversal() { InOrderTraversal(node); } /// <summary> /// 中序遍历 /// </summary> /// <param name="node"></param> private void InOrderTraversal(NoedSort node) { if (node == null) { return; } InOrderTraversal(node.Left); // 遍历左子树 Console.WriteLine(node.Value); // 访问根节点 InOrderTraversal(node.Right); // 遍历右子树 } /// <summary> /// 后序遍历 /// </summary> public void PostOrderTraversal() { PostOrderTraversal(node); } /// <summary> /// 后序遍历 /// </summary> /// <param name="node"></param> public void PostOrderTraversal(NoedSort node) { if (node == null) { return; } PostOrderTraversal(node.Left); // 遍历左子树 PostOrderTraversal(node.Right); // 遍历右子树 Console.WriteLine(node.Value); // 访问根节点 } }
标签:node,遍历,无聊,void,Value,二叉,NoedSort,排序,public From: https://www.cnblogs.com/changeMe/p/18338538