0

I'm a new one with C# and recenly I'm trying to write a C# program to present the Breadth-First Search algorithm for tree structure. Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;

 public class Node
    {
        public string NodeName { get; set; }
        public bool visited { get { return false; } set { visited = value; } }
        public LinkedList<Node> _item;
        public Node()
        {
            _item = new LinkedList<Node>();
        }
       public LinkedList<Node> Child { get { return _item; } set { _item = value; } }
    }
  public class Tree
    {
        public Node root;
        public Tree()
        {
            root = new Node { NodeName = "A" };
        }
    }
   public static class NodeExtension
    {   
       public static void BFS(this Node root, string name)
       {
            Node source = root.Child.Where(x => x.NodeName == "name").FirstOrDefault();
            Queue<Node> queue = new Queue<Node>();
            source.visited = true;
            queue.Enqueue(source);
            while (queue.Any())
            {
                Node u = queue.First();
                Console.WriteLine(u.NodeName);
                queue.Dequeue();
                LinkedList<Node> list = u.Child;
                foreach (Node v in list)
                {
                    if (v.visited == false)
                    {
                        v.visited = true;
                        queue.Enqueue(v);
                    }
                }
            }
       }
    }
 public class Program
    {
        public static void Main(string[] args)
        {
            Tree t = new Tree();
            t.root.Child.AddLast(new Node { NodeName = "B" });
            Node C = new Node { NodeName = "C" };
            C.Child.AddLast(new Node { NodeName = "D" });
            t.root.Child.AddLast(C);
            t.root.BFS("C");
             
        }
    }

But when I ran the code there was a message 'Object reference not set to an instance of object' at these 2 lines:

source.visited = true;

and this:

t.root.BFS("C");

I'm not sure what is the meaning of this error so can someone help me explain where did I do wrong? And how can I fix it please?

  • You do not have a node named `"name"` so the `Where` fails on `.Where(x => x.NodeName == "name")`. Then `.FirstOrDefault()` returns `null` and `source.visited` then throws. – Enigmativity Feb 06 '23 at 01:59
  • And do you have any idea what `public bool visited { get { return false; } set { visited = value; } }` will do when you actually have an instance that you do try to assign a value to `visited`? – Enigmativity Feb 06 '23 at 02:01

0 Answers0