天天看點

二叉樹

c#二叉樹

using System;

using System.Collections.Generic;

using System.Text;

namespace BinaryTreeTest

{

    class Node      //定義樹的節點

    {

        int _content;

        Node _leftLink;

        Node _rightLink;

        public Node(int content)

        {

            _content = content;

            _leftLink = null;

            _rightLink = null;

        }

        public int Content

            set { _content = value; }

            get { return _content; }

        public Node LeftLink

            get { return _leftLink; }

            set { _leftLink = value; }

        public Node RightLink

            get { return _rightLink; }

            set { _rightLink = value; }

    }

    class BinTree

        readonly Node root;

        public BinTree(int content)

            root = new Node(content);

        public void AddNode(int content)

            Node tNode = root;

            Node sNode = null;

            while (tNode != null)       //while循環用來定位要插入節點位置的父節點

            {

                sNode = tNode;          //sNode 用來記錄要插入節點的父節點

                if (content < tNode.Content)

                {

                    tNode = tNode.LeftLink;

                }

                else

                    tNode = tNode.RightLink;

            }

            if (content < sNode.Content)        //添加節點

                sNode.LeftLink = new Node(content);

            else

                sNode.RightLink = new Node(content);

        private void Print(Node aNode)  //中序周遊

            if (aNode.LeftLink != null)

                Print(aNode.LeftLink);

            Console.Write("{0}\t", aNode.Content);

            if (aNode.RightLink != null)

                Print(aNode.RightLink);

            }          

        public void PrintAll()

            Print(root);

    class Program

        static void Main(string[] args)

            Random rnd = new Random();

            BinTree t = new BinTree(rnd.Next(100));

            for (int i = 0; i < 9; i++)

                t.AddNode(rnd.Next(100));

            Console.WriteLine();

            t.PrintAll();

            Console.ReadLine();

}

繼續閱讀