以层序插入二叉树结点
这里以层序插入二叉树的结点,以先序遍历输出。
上一篇关于二叉树的内容在这里:http://lovedm.club/?id=110
using System; using System.Collections.Generic; namespace BTree { class Program { static void Main(string[] args) { Tree tree = new Tree(new Node(10));// 10 tree.InsertNode(new Node(9)); // / tree.InsertNode(new Node(8)); // 9 8 tree.InsertNode(new Node(7)); // / / tree.InsertNode(new Node(6)); // 7 6 5 4 tree.InsertNode(new Node(5)); // / tree.InsertNode(new Node(4)); // 3 tree.InsertNode(new Node(3)); // tree.PreTraversal(tree.root); Console.WriteLine("--------------"); tree.LevelOrderTraversal(tree.root); } } /// <summary> /// 树的节点 /// </summary> class Node { public int Value = 0; public Node Left; public Node Right; public Node(int value) { Value = value; } } /// <summary> /// 二叉树 /// </summary> class Tree { public readonly Node root; public Tree(Node node) { root = node; } /// <summary> /// 以层序进行插入结点 /// </summary> /// <param name="node"></param> public void InsertNode(Node node) { //使用队列 Queue<Node> queue = new Queue<Node>(); //首先根节点入队列 queue.Enqueue(root); //队列不为空一直循环 while (queue.Count != 0) { //出队列 Node tempNode = queue.Dequeue(); //左孩子不为空,那么将左孩子进队列;如果左孩子为空,则将结点挂到左孩子 if (tempNode.Left != null) { queue.Enqueue(tempNode.Left); } else { tempNode.Left = node; return; } //右孩子不为空,那么将右孩子进队列;如果右孩子为空,则将结点挂到右孩子 if (tempNode.Right != null) { queue.Enqueue(tempNode.Right); } else { tempNode.Right = node; return; } } } /// <summary> /// 先序遍历 /// </summary> /// <param name="node"></param> public void PreTraversal(Node node) { if (node == null) { return; } Console.WriteLine(node.Value); PreTraversal(node.Left); PreTraversal(node.Right); } public void LevelOrderTraversal(Node node) { Queue<Node> queue = new Queue<Node>(); queue.Enqueue(node); while (queue.Count != 0) { Node tempNode = queue.Dequeue(); Console.WriteLine(tempNode.Value); if (tempNode.Left != null) { queue.Enqueue(tempNode.Left); } if (tempNode.Right != null) { queue.Enqueue(tempNode.Right); } } } } }