代码改变世界

二叉树

2014-05-14 16:04  STARSIX03  阅读(122)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;

namespace BinaryTree
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new BinaryTree("ABCDEF");
            a.First(a.Head);
            Console.WriteLine();
            a.Level();
            Console.ReadLine();
        }
    }

    public class Node
    {
        private object _data;
        public Node(object data)
        {
            _data = data;
        }

        public Node Left { get; set; }//左子结点

        public Node Right { get; set; }//右子结点

        public override string ToString()
        {
            return _data.ToString();
        }
    }

    public class BinaryTree
    {
        private Node _head;
        private string _cStor;
        public Node Head
        {
            get { return _head; }
        }

        public BinaryTree(string str)
        {
            _cStor = str;
            _head = new Node(_cStor[0]);
            Add(_head,0);

        }

        public void Add(Node parent,int index)
        {
            int left = index*2 + 1;
            if(left < _cStor.Length)
            {
                if(_cStor[left] != '#')
                {
                    parent.Left = new Node(_cStor[left]);
                    Add(parent.Left,left);
                }
            }

            int right = index*2 + 2;
            if(right < _cStor.Length)
            {
                if(_cStor[right] != '#')//#为空结点
                {
                    parent.Right = new Node(_cStor[right]);
                    Add(parent.Right,right);
                }
            }
        }

        public void First(Node parent)//深度优先遍历
        {
            if (parent != null)
            {
                Console.Write(parent);
                First(parent.Left);
                First(parent.Right);
            }
        }

        public void Level()//广度优先遍历
        {
            var queue = new Queue<Node>();
            queue.Enqueue(_head);
           
            while (queue.Count > 0)
            {
                var node = queue.Dequeue();
                Console.Write(node);
                if(node.Left != null)
                    queue.Enqueue(node.Left);
                if(node.Right != null)
                    queue.Enqueue(node.Right);
            }
        }
    }
}