DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Aniruddha has posted 40 posts at DZone. View Full User Profile

Breadth First Search - C#

06.01.2012
| 8381 views |
  • submit to reddit
class BinaryTreeNode
        {
            public BinaryTreeNode Left { get; set; }

            public BinaryTreeNode Right { get; set; }

            public int Data { get; set; }
        }


        public class BreadthFirstSearch
        {
            private Queue<BinaryTreeNode> _searchQueue;
            private BinaryTreeNode _root;

            public BreadthFirstSearch(BinaryTreeNode rootNode)
            {
                _searchQueue = new Queue<BinaryTreeNode>();
                _root = rootNode;
            }

            public bool Search(int data)
            {
                BinaryTreeNode _current = _root;
                _searchQueue.Enqueue(_root);

                while (_searchQueue.Count != 0)
                {
                    _current = _searchQueue.Dequeue();
                    if (__current.Data == data)
                    {
                        return true;
                    }
                    else
                    {
                        _searchQueue.Enqueue(_current.Left);
                        _searchQueue.Enqueue(_current.Right);
                    }
                }

                return false;
            }
        }
Breadth First Search using C#