C#实现多叉树的构建和遍历

翻到了很早之前帮朋友做了一份C#实现二叉的代码,今天就把它扩建成多叉并且加上了先序遍历和按层遍历,以后会慢慢完善这份代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {               
        static void Main(string[] args)
        {
            tree head = new tree(1);
            //构建一个三层,以head为根的三叉树,节点默认值为1
            buildTree(3, head, 3,1);
            readTree(head);
            bfsTree(head);
        }

        //构建空树 floors:构建层数 head:根节点 sonnumber:子节点数量 sonvalue:子节点值
        static void buildTree(int floors, tree head,int sonnumber,int sonvalue)
        {
            if (floors == 1)
                return;
            head.child = new List<tree>();
            for(int i=0;i!=sonnumber;i++)
                head.child.Add(new tree(sonvalue+1));
            foreach (tree temp_tree in head.child)
                buildTree(floors - 1, temp_tree, sonnumber, sonvalue+1);
        }
        //先序遍历
        static void readTree(tree head)
        {
            Console.WriteLine(head.value);
            if (head.child != null)
            {
                foreach (tree temp_tree in head.child)
                    readTree(temp_tree);
            }
        }
        //按层遍历
        static void bfsTree(tree head)
        {
            Queue<tree> queueTree = new Queue<tree>();
            queueTree.Enqueue(head);
            while (queueTree.Count != 0)
            {
                Console.WriteLine(queueTree.Peek().value);
                if (queueTree.Peek().child != null)
                {
                    foreach (tree temp_tree in queueTree.Peek().child)
                    {
                        queueTree.Enqueue(temp_tree);
                    }
                }
                queueTree.Dequeue();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class tree
    {
        public int value;
        public List<tree> child;

        public tree(int treeValue)
        {
            value = treeValue;
        }
    }
}

 

发表评论

电子邮件地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据