juin

21

Posted by : admin | On : 21 juin 2016

In this article we’ll demontrate usage of graph , binary trees , and tree

As well as BFS (common neighor first search before doing a drill down on the first node ) and dFS (deep search ) pattern

Common Tree

using System;
using System.Collections.Generic;

public class TreeNode<T>
{
	private T value;
	private bool hasParent;
	private List<TreeNode<T>> children;

	public TreeNode(T value)
	{
		if (value == null)
		{
			throw new ArgumentNullException("Cannot insert null value!");
		}
		this.value = value;
		this.children = new List<TreeNode<T>>();
	}

	public T Value
	{
		get{return this.value;}
		set{this.value = value;}
	}

	public int ChildrenCount
	{
		get{return this.children.Count;}
	}

	public void AddChild(TreeNode<T> child)
	{
		if (child == null)
		{
			throw new ArgumentNullException("Cannot insert null value!");
		}

		if (child.hasParent)
		{
			throw new ArgumentException("The node already has a parent!");
		}
		child.hasParent = true;
		this.children.Add(child);
	}

	public TreeNode<T> GetChild(int index)
	{
		return this.children[index];
	}
}

public class Tree<T>
{
	private TreeNode<T> root;

	public Tree(T value)
	{
		if (value == null)
		{
			throw new ArgumentNullException("Cannot insert null value!");
		}
		this.root = new TreeNode<T>(value);
	}

	public Tree(T value, params Tree<T>[] children) : this(value)
	{
		foreach (Tree<T> child in children)
		{
			this.root.AddChild(child.root);
		}
	}

	/// <summary>
	/// The root node or null if the tree is empty
	/// </summary>
	public TreeNode<T> Root
	{
		get{return this.root;}
	}

	private void TraverseDFS(TreeNode<T> root, string spaces)
	{
		if (this.root == null)
		{
			return;
		}

		Console.WriteLine(spaces + root.Value);

		TreeNode<T> child = null;
		for (int i = 0; i < root.ChildrenCount; i++)
		{
			child = root.GetChild(i);
			TraverseDFS(child, spaces + "   ");
		}
	}

	public void TraverseDFS()
	{
		this.TraverseDFS(this.root, string.Empty);
	}

	public void TraverseBFS()
	{
		Queue<TreeNode<T>> queue = new Queue<TreeNode<T>>();
		queue.Enqueue(this.root);
		while (queue.Count > 0)
		{
			TreeNode<T> currentNode = queue.Dequeue();
			Console.Write("{0} ", currentNode.Value);
			for (int i = 0; i < currentNode.ChildrenCount; i++)
			{
				TreeNode<T> childNode = currentNode.GetChild(i);
				queue.Enqueue(childNode);
			}
		}
	}

	public void TraverseDFSWithStack()
	{
		Stack<TreeNode<T>> stack = new Stack<TreeNode<T>>();
		stack.Push(this.root);
		while (stack.Count > 0)
		{
			TreeNode<T> currentNode = stack.Pop();
			Console.Write("{0} ", currentNode.Value);
			for (int i = 0; i < currentNode.ChildrenCount; i++)
			{
				TreeNode<T> childNode = currentNode.GetChild(i);
				stack.Push(childNode);
			}
		}
	}
}

public static class TreeExample
{
	static void Main()
	{
		Tree<int> tree =
			new Tree<int>(7,
				new Tree<int>(19,
					new Tree<int>(1),
					new Tree<int>(12),
					new Tree<int>(31)),
				new Tree<int>(21),
				new Tree<int>(14,
					new Tree<int>(23),
					new Tree<int>(6))
			);

		Console.WriteLine("Depth-First Search (DFS) traversal (recursive):");
		tree.TraverseDFS();
		Console.WriteLine();

		Console.WriteLine("Breadth-First Search (BFS) traversal (with queue):");
		tree.TraverseBFS();
		Console.WriteLine();

		Console.WriteLine();
		Console.WriteLine("Depth-First Search (DFS) traversal (with stack):");
		tree.TraverseDFSWithStack();
		Console.WriteLine();
        Console.Read();
	}
}

Binary Tree

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoTest
{
    public class BinarySearchTree<T> where T : IComparable<T>
    {
        private BinaryTreeNode<T> root;
        public BinarySearchTree()
        {
            this.root = null;
        }
        public void Insert(T value)
        {
            this.root = Insert(value, null, root);
        }
        private BinaryTreeNode<T> Insert(T value,BinaryTreeNode<T> parentNode, BinaryTreeNode<T> node)
        {
            if (node == null)
            {
                node = new BinaryTreeNode<T>(value);
                node.parent = parentNode;
            }
            else
            {
                int compareTo = value.CompareTo(node.value);
                if (compareTo < 0)
                {
                    node.leftChild =Insert(value, node, node.leftChild);
                }
                else if (compareTo > 0)
                {
                    node.rightChild =Insert(value, node, node.rightChild);
                }
            }
            return node;
        }
        private BinaryTreeNode<T> Find(T value)
        {
            BinaryTreeNode<T> node = this.root;
            while (node != null)
            {
                int compareTo = value.CompareTo(node.value);
                if (compareTo < 0)
                {
                    node = node.leftChild;
                }
                else if (compareTo > 0)
                {
                    node = node.rightChild;
                }
                else
                {
                    break;
                }
            }
            return node;
        }
        public void PrintTreeDFS()
        {
            PrintTreeDFS(this.root);
            Console.WriteLine();
        }
        private void PrintTreeDFS(BinaryTreeNode<T> node)
        {
            if (node != null)
            {
                PrintTreeDFS(node.leftChild);
                Console.Write(node.value + " ");
                PrintTreeDFS(node.rightChild);
            }
        }
        internal class BinaryTreeNode<T> : IComparable<BinaryTreeNode<T>> where T : IComparable<T>
        {
            // Contains the value of the node
            internal T value;

            // Contains the parent of the node
            internal BinaryTreeNode<T> parent;

            // Contains the left child of the node
            internal BinaryTreeNode<T> leftChild;

            // Contains the right child of the node
            internal BinaryTreeNode<T> rightChild;

            /// <summary>Constructs the tree node</summary>
            /// <param name="value">The value of the tree node</param>
            public BinaryTreeNode(T value)
            {
                if (value == null)
                {
                    throw new ArgumentNullException("Cannot insert null value!");
                }
                this.value = value;
                this.parent = null;
                this.leftChild = null;
                this.rightChild = null;
            }
            public override string ToString()
            {
                return this.value.ToString();
            }
            public override int GetHashCode()
            {
                return this.value.GetHashCode();
            }

            public override bool Equals(object obj)
            {
                BinaryTreeNode<T> other = (BinaryTreeNode<T>)obj;
                return this.CompareTo(other) == 0;
            }

            public int CompareTo(BinaryTreeNode<T> other)
            {
                return this.value.CompareTo(other.value);
            }
        }
    }
}

Graphe

using System;
using System.Collections.Generic;

public class Graph
{
	internal const int MaxNode = 1024;
	private int[][] childNodes;

	public Graph(int[][] childNodes)
	{
		this.childNodes = childNodes;
	}

	public void TraverseBFS(int node)
	{
		bool[] visited = new bool[MaxNode];
		Queue<int> queue = new Queue<int>();
		queue.Enqueue(node);
		visited[node] = true;
		while (queue.Count > 0)
		{
			int currentNode = queue.Dequeue();
			Console.Write("{0} ", currentNode);
			foreach (int childNode in childNodes[currentNode])
			{
				if (!visited[childNode])
				{
					queue.Enqueue(childNode);
					visited[childNode] = true;
				}
			}
		}
	}

	public void TraverseDFS(int node)
	{
		bool[] visited = new bool[MaxNode];
		Stack<int> stack = new Stack<int>();
		stack.Push(node);
		visited[node] = true;
		while (stack.Count > 0)
		{
			int currentNode = stack.Pop();
			Console.Write("{0} ", currentNode);
			foreach (int childNode in childNodes[currentNode])
			{
				if (!visited[childNode])
				{
					stack.Push(childNode);
					visited[childNode] = true;
				}
			}
		}
	}

	public void TraverseDFSRecursive(int node, bool[] visited)
	{
		if (!visited[node])
		{
			visited[node] = true;
			Console.Write("{0} ", node);
			foreach (int childNode in childNodes[node])
			{
				TraverseDFSRecursive(childNode, visited);
			}
		}
	}
}

class GraphExample
{
	static void Main()
	{
		Graph g = new Graph(new int[][] {
			new int[] {3, 6}, // successors of vertice 0
			new int[] {2, 3, 4, 5, 6}, // successors of vertice 1
			new int[] {1, 4, 5}, // successors of vertice 2
			new int[] {0, 1, 5}, // successors of vertice 3
			new int[] {1, 2, 6}, // successors of vertice 4
			new int[] {1, 2, 3}, // successors of vertice 5
			new int[] {0, 1, 4}  // successors of vertice 6
		});

		Console.Write("Breadth-First Search (BFS) traversal: ");
		g.TraverseBFS(0);
		Console.WriteLine();

		Console.Write("Depth-First Search (DFS) traversal (with stack): ");
		g.TraverseDFS(0);
		Console.WriteLine();

		Console.Write("Depth-First Search (DFS) traversal (recursive): ");
		bool[] visited = new bool[Graph.MaxNode];
		g.TraverseDFSRecursive(0, visited);
		Console.WriteLine();
	}
}

Good tuto

http://www.introprogramming.info/tag/graph-implementation/#_Toc362296541