Esempio n. 1
0
        public void Find_ItemFound_ReturnsFoundItem()
        {
            var myOrganizationTree = new NaryTree <string>();
            var added = false;
            NaryTreeNode <string> foundNode = null;

            //root of the tree should be null
            Assert.IsTrue(myOrganizationTree.IsEmpty());

            //create a children list
            var Children = new List <NaryTreeNode <string> >()
            {
                new NaryTreeNode <string>("Kim"),
                new NaryTreeNode <string>("Kate"),
                new NaryTreeNode <string>("Mikesh")
            };

            //add root node Jimmy with children
            added = myOrganizationTree.InsertTopLevelWithChildren("Jimmy", Children);

            //should return true as it was added
            Assert.IsTrue(added);

            //Find Mikesh node it's children list should be 0 before inserting Timmy
            foundNode = myOrganizationTree.Find("Mikesh");

            Assert.IsNotNull(foundNode);

            if (foundNode != null)
            {
                Assert.IsTrue(foundNode.Data == "Mikesh");
                Assert.IsTrue(foundNode.ChildrenList.Count == 0);
            }
        }
        public static void TestAncestorOfTwoNodesInNaryTree()
        {
            NaryTreeNode <char> root   = new NaryTreeNode <char>('A');
            NaryTreeNode <char> child1 = new NaryTreeNode <char>('B');
            NaryTreeNode <char> child2 = new NaryTreeNode <char>('C');
            NaryTreeNode <char> child3 = new NaryTreeNode <char>('D');
            NaryTreeNode <char> child4 = new NaryTreeNode <char>('E');

            root.Children.Add(child1);
            root.Children.Add(child2);
            root.Children.Add(child3);
            root.Children.Add(child4);

            NaryTreeNode <char> child5 = new NaryTreeNode <char>('F');
            NaryTreeNode <char> child6 = new NaryTreeNode <char>('G');

            child2.Children.Add(child5);
            child2.Children.Add(child6);
            NaryTreeNode <char> child7 = new NaryTreeNode <char>('H');

            child3.Children.Add(child7);

            Console.WriteLine("The LCA of {0} and {1} is {2}. Expected:{3}", child5, child6, GetLCA(root, child5, child6), child2);
            Console.WriteLine("The LCA of {0} and {1} is {2}. Expected:{3}", child5, child3, GetLCA(root, child5, child3), root);
            Console.WriteLine("The LCA of {0} and {1} is {2}. Expected:{3}", child2, child6, GetLCA(root, child2, child6), child2);
            Console.WriteLine("The LCA of {0} and {1} is {2}. Expected:{3}", child1, child4, GetLCA(root, child1, child4), root);
        }
Esempio n. 3
0
        public int MaxDepth(NaryTreeNode root)
        {
            if (root == null)
            {
                return(0);
            }
            Queue <NaryTreeNode> q = new Queue <NaryTreeNode>();

            q.Enqueue(root);
            int maxDepth = 0;

            while (q.Count > 0)
            {
                int size = q.Count;
                while (size-- > 0)
                {
                    NaryTreeNode node = q.Dequeue();
                    foreach (var child in node.children)
                    {
                        q.Enqueue(child);
                    }
                }
                maxDepth++;
            }
            return(maxDepth);
        }
        /// <summary>
        /// This is a recursive subroutine to get the LCA in an Nary tree.
        /// For example the following nary tree
        ///           A
        ///			  |
        ///---------------------------------
        ///|        |              |       |
        ///B        C              D       E
        ///         |              |
        ///	  ----------		   H
        ///	 |         |
        ///  F         G
        ///
        /// this tree will be serilaized as
        /// A B ) C F ) G ) ) D H ) ) E ) )
        ///
        /// The running time is O(n)
        /// The space requirement is also O(n) for an unbalanced tree.
        /// </summary>
        /// <param name="root"></param>
        /// <param name="node1"></param>
        /// <param name="node2"></param>
        /// <returns></returns>
        static NaryTreeNode <char> GetLCA(NaryTreeNode <char> root, NaryTreeNode <char> node1, NaryTreeNode <char> node2)
        {
            if (root == null)
            {
                return(null);
            }
            if (root == node1 || root == node2)
            {
                return(root);
            }

            NaryTreeNode <char> lastLCA = null;
            int numOfElementFound       = 0;

            foreach (NaryTreeNode <char> n in root.Children)
            {
                NaryTreeNode <char> lca = GetLCA(n, node1, node2);
                if (lca != null)
                {
                    numOfElementFound++;
                    if (lastLCA == null)
                    {
                        // We have already found the LCA and we need to return the last found LCA
                        lastLCA = lca;
                    }
                }
            }
            if (numOfElementFound == 2)
            {
                // root in this case is the LCA
                return(root);
            }
            return(lastLCA);
        }
Esempio n. 5
0
        public NaryTreeNode <T> Find(T item)
        {
            //case of empty tree
            if (root == null)
            {
                return(null);
            }

            //found at root
            if (root.Data.Equals(item))
            {
                return(root);
            }

            var queue = new Queue <NaryTreeNode <T> >();
            var found = false;

            //current node when traversing the tree
            NaryTreeNode <T> current = null;

            //holds the value of the found item
            NaryTreeNode <T> foundItem = null;

            //add root to the queue
            queue.Enqueue(root);

            //while the queue is not empty and item is found
            while (queue.Count() != 0 && !found)
            {
                //remove the first node in the queue
                current = queue.Dequeue();

                //current node is not null
                if (current != null)
                {
                    //if found
                    if (current.Data.Equals(item))
                    {
                        found     = true;
                        foundItem = current;
                    }
                    //not found at the current level so add its children
                    else
                    {
                        //add its children if they have any to the queue
                        if (current.ChildrenList != null)
                        {
                            foreach (var child in current.ChildrenList)
                            {
                                queue.Enqueue(child);
                            }
                        }
                    }
                }
            }

            return(foundItem);
        }
Esempio n. 6
0
        public void InsertTopLevel_NonEmptyTree_ReturnsTrue()
        {
            var myOrganizationTree = new NaryTree <string>("Jimmy");
            var added = false;
            NaryTreeNode <string> foundNode = null;

            //root of the tree should not be null
            Assert.IsFalse(myOrganizationTree.IsEmpty());

            //add Kim to Jimmy(Root)
            added = myOrganizationTree.InsertTopLevel("Kim");
            Assert.IsTrue(added);

            //find the root
            foundNode = myOrganizationTree.Find("Jimmy");

            if (foundNode != null)
            {
                Assert.IsTrue(foundNode.Data == "Jimmy");

                //Added Kim to Jimmy's Children list
                Assert.IsTrue(foundNode.ChildrenList.Count == 1);
                Assert.IsTrue(foundNode.ChildrenList[0].Data == "Kim");
            }

            added = myOrganizationTree.InsertTopLevel("Kate");
            Assert.IsTrue(added);

            //find the root
            foundNode = myOrganizationTree.Find("Jimmy");

            if (foundNode != null)
            {
                Assert.IsTrue(foundNode.Data == "Jimmy");

                //Added Kim to Jimmy's Children list
                Assert.IsTrue(foundNode.ChildrenList.Count == 2);
                Assert.IsTrue(foundNode.ChildrenList[0].Data == "Kim");
                Assert.IsTrue(foundNode.ChildrenList[1].Data == "Kate");
            }


            added = myOrganizationTree.InsertTopLevel("Mikesh");
            //find the root
            foundNode = myOrganizationTree.Find("Jimmy");

            if (foundNode != null)
            {
                Assert.IsTrue(foundNode.Data == "Jimmy");

                //Added Kim to Jimmy's Children list
                Assert.IsTrue(foundNode.ChildrenList.Count == 3);
                Assert.IsTrue(foundNode.ChildrenList[0].Data == "Kim");
                Assert.IsTrue(foundNode.ChildrenList[1].Data == "Kate");
                Assert.IsTrue(foundNode.ChildrenList[2].Data == "Mikesh");
            }
        }
Esempio n. 7
0
        public static void TestSerializeDeserializeAnNaryTree()
        {
            string serializedTree = "1 2 ) 3 6 ) 7 ) ) 4 8 ) ) 5 ) )";

            string[]           allNodes = serializedTree.Split(' ');
            NaryTreeNode <int> node     = DeSerialize(allNodes);

            StringBuilder sb = new StringBuilder();

            Serialize(node, sb);
            Console.WriteLine("Expected Serialized tree is {0}. Actual Serialized tree is {1}", serializedTree, sb.ToString());
        }
Esempio n. 8
0
        public void Remove_ItemNotRoot_ReturnsTrue()
        {
            var myOrganizationTree = new NaryTree <string>();
            var added = false;
            NaryTreeNode <string> foundNode = null;

            //root of the tree should be null
            Assert.IsTrue(myOrganizationTree.IsEmpty());

            //create a children list
            var Children = new List <NaryTreeNode <string> >()
            {
                new NaryTreeNode <string>("Kim"),
                new NaryTreeNode <string>("Kate"),
                new NaryTreeNode <string>("Mikesh")
            };

            //add some children to Kate
            Children[1].ChildrenList.Add(new NaryTreeNode <string>("Jack"));
            Children[1].ChildrenList.Add(new NaryTreeNode <string>("Peter"));
            Children[1].ChildrenList[1].ChildrenList.Add(new NaryTreeNode <string>("Mike"));


            //add root node Jimmy with children
            added = myOrganizationTree.InsertTopLevelWithChildren("Jimmy", Children);

            //should return true as it was added
            Assert.IsTrue(added);

            //Find Kate
            foundNode = myOrganizationTree.Find("Kate");

            Assert.IsNotNull(foundNode);

            if (foundNode != null)
            {
                Assert.IsTrue(foundNode.Data == "Kate");
                Assert.IsTrue(foundNode.ChildrenList.Count == 2);
                Assert.IsTrue(foundNode.ChildrenList[0].Data == "Jack");
                Assert.IsTrue(foundNode.ChildrenList[1].Data == "Peter");
            }

            //Remove Kate
            var removed = myOrganizationTree.Remove("Kate");

            Assert.IsTrue(removed);

            foundNode = myOrganizationTree.Find("Kate");

            //Kate should not be found
            Assert.IsNull(foundNode);
        }
Esempio n. 9
0
 public static void Serialize(NaryTreeNode <int> node, StringBuilder sb)
 {
     if (node == null)
     {
         return;
     }
     sb.Append(string.Format("{0} ", node.Data));
     foreach (NaryTreeNode <int> child in node.Children)
     {
         Serialize(child, sb);
     }
     sb.Append(") ");
 }
Esempio n. 10
0
        public void InsertTopLevelWithChildren_NonEmptyTree_ReturnsTrue()
        {
            var myOrganizationTree = new NaryTree <string>("Jimmy");
            var added = false;
            NaryTreeNode <string> foundNode = null;

            //root of the tree should be not null
            Assert.IsFalse(myOrganizationTree.IsEmpty());

            //find the root which is Jimmy and should have no children
            foundNode = myOrganizationTree.Find("Jimmy");

            Assert.IsNotNull(foundNode);

            if (foundNode != null)
            {
                Assert.IsTrue(foundNode.Data == "Jimmy");
                Assert.IsTrue(foundNode.ChildrenList.Count == 0);
            }


            //create a children list
            var Children = new List <NaryTreeNode <string> >()
            {
                new NaryTreeNode <string>("Kim"),
                new NaryTreeNode <string>("Kate"),
                new NaryTreeNode <string>("Mikesh")
            };



            //add root node Jimmy with children
            added = myOrganizationTree.InsertTopLevelWithChildren("Timmy", Children);

            //should return true as it was added
            Assert.IsTrue(added);

            foundNode = myOrganizationTree.Find("Timmy");

            //should find it
            Assert.IsNotNull(foundNode);

            if (foundNode != null)
            {
                Assert.IsTrue(foundNode.Data == "Timmy");
                Assert.IsTrue(foundNode.ChildrenList.Count == 3);
                Assert.IsTrue(foundNode.ChildrenList[0].Data == "Kim");
                Assert.IsTrue(foundNode.ChildrenList[1].Data == "Kate");
                Assert.IsTrue(foundNode.ChildrenList[2].Data == "Mikesh");
            }
        }
Esempio n. 11
0
        public void CreateData()
        {
            node          = new NaryTreeNode();
            node.val      = 1;
            node.children = new List <NaryTreeNode>();
            var node3       = new NaryTreeNode(3, new List <NaryTreeNode>());
            var node3Child1 = new NaryTreeNode(5, null);
            var node3Child2 = new NaryTreeNode(6, null);

            node3.children.Add(node3Child1);
            node3.children.Add(node3Child2);
            node.children.Add(node3);
            node.children.Add(new NaryTreeNode(2, null));
            node.children.Add(new NaryTreeNode(4, null));
        }
Esempio n. 12
0
 public IList <int> PostOrder(NaryTreeNode root)
 {
     //NaryTreeNode pointer = root;
     if (root == null)
     {
         return(postOrderTraversalList);
     }
     postOrderTraversalList.Add(root.val);
     if (root.children != null)
     {
         foreach (var child in root.children)
         {
             PostOrder(child);
         }
     }
     return(postOrderTraversalList);
 }
Esempio n. 13
0
        private void LevelOrderHelper(NaryTreeNode root, int height)
        {
            if (root == null)
            {
                return;
            }
            if (height == levelOrderTraversalListOfLevelLists.Count)
            {
                levelOrderTraversalListOfLevelLists.Add(new List <int>());
            }

            levelOrderTraversalListOfLevelLists[height].Add(root.val);
            foreach (var child in root.children)
            {
                LevelOrderHelper(child, height + 1);
            }
        }
Esempio n. 14
0
        public bool Insert(T item, T value)
        {
            var added   = false;
            var newNode = new NaryTreeNode <T>(value);

            var found = Find(item);

            //found the node
            if (found != null)
            {
                if (found.ChildrenList != null)
                {
                    found.ChildrenList.Add(newNode);
                    added = true;
                }
            }

            return(added);
        }
Esempio n. 15
0
        public void Remove_Root_ReturnsTrue()
        {
            var myOrganizationTree = new NaryTree <string>();
            var added = false;
            NaryTreeNode <string> foundNode = null;

            //root of the tree should be null
            Assert.IsTrue(myOrganizationTree.IsEmpty());

            //create a children list
            var Children = new List <NaryTreeNode <string> >()
            {
                new NaryTreeNode <string>("Kim"),
                new NaryTreeNode <string>("Kate"),
                new NaryTreeNode <string>("Mikesh")
            };

            //add root node Jimmy with children
            added = myOrganizationTree.InsertTopLevelWithChildren("Jimmy", Children);

            //should return true as it was added
            Assert.IsTrue(added);

            //Find Root Jimmy
            foundNode = myOrganizationTree.Find("Jimmy");

            Assert.IsNotNull(foundNode);

            if (foundNode != null)
            {
                Assert.IsTrue(foundNode.Data == "Jimmy");
                Assert.IsTrue(foundNode.ChildrenList.Count == 3);
                Assert.IsTrue(foundNode.ChildrenList[0].Data == "Kim");
                Assert.IsTrue(foundNode.ChildrenList[1].Data == "Kate");
                Assert.IsTrue(foundNode.ChildrenList[2].Data == "Mikesh");
            }

            //Remove the root
            myOrganizationTree.Remove("Jimmy");

            //root of the tree should be null after removing root
            Assert.IsTrue(myOrganizationTree.IsEmpty());
        }
Esempio n. 16
0
        public bool InsertTopLevelWithChildren(T item, List <NaryTreeNode <T> > children)
        {
            var added   = false;
            var newNode = new NaryTreeNode <T>(item, children);


            if (root != null)
            {
                root.ChildrenList.Add(newNode);
                added = true;
            }

            //node becomes the new root
            else
            {
                root  = newNode;
                added = true;
            }

            return(added);
        }
Esempio n. 17
0
        public void PrintTree()
        {
            if (root == null)
            {
                Console.WriteLine("Empty Tree");
            }

            var queue = new Queue <NaryTreeNode <T> >();

            NaryTreeNode <T> current = null;

            queue.Enqueue(root);

            //while the queue is not empty
            while (queue.Count() != 0)
            {
                //remove the first node in the queue
                current = queue.Dequeue();

                //current node is not null
                if (current != null)
                {
                    //print it
                    Console.Write(current.Data);

                    //add its children if they have any to the queue
                    if (current.ChildrenList != null)
                    {
                        foreach (var child in current.ChildrenList)
                        {
                            queue.Enqueue(child);
                        }
                    }
                }

                Console.WriteLine();
            }
        }
Esempio n. 18
0
        public static NaryTreeNode <int> DeSerialize(string[] allNodes)
        {
            Stack <NaryTreeNode <int> > st = new Stack <NaryTreeNode <int> >();

            st.Push(new NaryTreeNode <int>(int.Parse(allNodes[0])));
            NaryTreeNode <int> root = null;

            for (int index = 1; index < allNodes.Length; index++)
            {
                if (allNodes[index] == ")")
                {
                    root = st.Pop();
                }
                else
                {
                    NaryTreeNode <int> currentNode = new NaryTreeNode <int>(int.Parse(allNodes[index]));
                    st.Peek().Children.Add(currentNode);
                    st.Push(currentNode);
                }
            }

            return(root);
        }
Esempio n. 19
0
 /// <summary>
 /// Constructor that takes in the data for the root of the tree
 /// </summary>
 /// <param name="data"></param>
 public NaryTree(T data)
 {
     root = new NaryTreeNode <T>(data);
 }
Esempio n. 20
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 public NaryTree()
 {
     root = null;
 }
Esempio n. 21
0
        public bool Remove(T item)
        {
            var removed = false;
            var found   = false;
            NaryTreeNode <T> current     = null;
            NaryTreeNode <T> removedNode = null;
            var queue = new Queue <NaryTreeNode <T> >();

            //base case empty tree
            if (IsEmpty())
            {
                return(true);
            }

            //case delete at root removes all children
            if (root != null && root.Data.Equals(item))
            {
                Clear();
                return(true);
            }

            queue.Enqueue(root);

            while (queue.Count != 0 && !found)
            {
                current = queue.Dequeue();

                if (current != null)
                {
                    //found it so exit
                    if (current.Data.Equals(item))
                    {
                        found       = true;
                        removedNode = current;
                    }
                    //not found so check the children of the node
                    else
                    {
                        if (current.ChildrenList != null)
                        {
                            foreach (var child in current.ChildrenList)
                            {
                                if (child.Data.Equals(item))
                                {
                                    found       = true;
                                    removedNode = child;
                                    break;
                                }

                                //children list is not null queue it
                                else if (child.ChildrenList.Count != 0)
                                {
                                    queue.Enqueue(child);
                                }
                            }
                        }
                    }
                }
            }

            //remove the node
            if (removedNode != null && current != null && current.ChildrenList != null)
            {
                current.ChildrenList.Remove(removedNode);
                removed = true;
            }

            return(removed);
        }
Esempio n. 22
0
 public IList <IList <int> > LevelOrder(NaryTreeNode root)
 {
     LevelOrderHelper(root, 0);
     return(levelOrderTraversalListOfLevelLists);
 }
Esempio n. 23
0
 public void Clear()
 {
     root = null;
 }