0

I tried creating a Binary tree assuming it will have max of 2 child nodes. But for a graph it will have one or more graph nodes connected to it. How can I create a simple class for a graph node like the below which I created for a tree. The reason for suggestion is because I am trying for a simple code to find all nodes info tied to a particular node.

class TreeNode
{
    public int value { get; set; }
    public TreeNode leftNode { get; set; }
    public TreeNode rightNode { get; set; }

}
2
  • 1
    With a List<TreeNode> ? Commented Aug 13, 2017 at 20:40
  • The value in this case is an array int[] value if the graph contains only y points. Commented Aug 13, 2017 at 21:18

1 Answer 1

2

In case of graph, any node can have arbitrary many edges (neighbor nodes), so you have to use a collection, say List<T>:

// TValue - let's generalize 
// (e.g. you may want ot have double or string value associated with the node)
class GraphNode<TValue> {
    private List<GraphNode<TValue>> m_Connected = new List<GraphNode<TValue>>();

    public TValue value { get; set; }

    // get (and no set) - we don't want to assign the collection as whole
    // if we want to add/remove a neighbor we'll call Neighbors.Add, Neighbors.Remove
    public List<GraphNode<TValue>> Neighbors { 
      get {
        return m_Connected;
      }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.