using System; using System.Collections.Generic; using System.Text; namespace VisitTree { class Program { static void Main(string[] args) { //consuct a tree to test this algorithm Tree tree = new Tree(); string inputData = Console.ReadLine(); char[] inputArray = inputData.ToCharArray(); foreach (char data in inputArray) { tree.AddNodeToTree(int.Parse(data.ToString())); } WideVisitTree(tree); Console.ReadKey(); } //wide visit tree public static void WideVisitTree(Tree tree) { TreeNode visited; TreeNode tempNode = tree.Root; Quence container = new Quence(); if (tree.Root == null) return; container.EnQuence(tempNode); while (!container.isEmpty()) { container.DeQuence(out visited); Console.Write(visited.Data.ToString()); if (visited.Lift != null) container.EnQuence(visited.Lift); if (visited.Right != null) container.EnQuence(visited.Right); } } } //construct a tree data structure class TreeNode { int data; TreeNode lift; TreeNode right; public int Data { get { return data; } set { data = value; } } public TreeNode Lift { get { return lift; } set { lift = value; } } public TreeNode Right { get { return right; } set { right = value; } } } class Tree { TreeNode root = null; public TreeNode Root { get { return root; } } public void AddNodeToTree(int data) { TreeNode temp = new TreeNode(); temp.Data = data; temp.Lift = null; temp.Right = null; if (root == null) { root = temp; } else { visitnode(root, temp); } } public void visitnode(TreeNode root, TreeNode node) { while(node.Data < root.Data) { if (root.Lift == null) { root.Lift = node; return; } root = root.Lift; } while (node.Data >= root.Data) { if (root.Right == null) { root.Right = node; return; } root = root.Right; } visitnode(root,node); } } //Quence node class class QuenceNode { TreeNode node; QuenceNode next; public TreeNode Node { get { return node; } set { node = value; } } public QuenceNode Next { get { return next; } set { next = value; } } } class Quence { QuenceNode head = null; QuenceNode tail = null; public void EnQuence(TreeNode node) { QuenceNode temp = new QuenceNode(); temp.Node = node; temp.Next = null; if (head == null && tail == null) { head = temp; tail = temp; } else { tail.Next = temp; tail = temp; } } public void DeQuence(out TreeNode node) { if (head == null && tail == null) { node = null; return; } if (head == tail && head != null) { node = head.Node; head = null; tail = null; } else { node = head.Node; head = head.Next; } } public bool isEmpty() { if (head == null && tail == null) return true; else return false; } } }