예제 #1
0
        /// <summary>
        /// We can use 2 linked list to do the operation in BFS fashion.
        ///
        /// </summary>
        /// <param name="head"></param>
        /// <returns></returns>
        public static List <SinglyLinkedList <BinaryTreeNode <int> > > CreateLinkedListOfTreeNodesAtEachDepth(BinaryTreeNode <int> head)
        {
            // the list of the linkedlist of nodes at each level
            List <SinglyLinkedList <BinaryTreeNode <int> > > retList = new List <SinglyLinkedList <BinaryTreeNode <int> > >();

            SinglyLinkedList <BinaryTreeNode <int> > lastLinkedList = new SinglyLinkedList <BinaryTreeNode <int> >();

            lastLinkedList.AppendToEnd(head);
            while (lastLinkedList.Head != null)
            {
                SingleLinkedListNode <BinaryTreeNode <int> > lastLinkedListNode = lastLinkedList.Head;
                SinglyLinkedList <BinaryTreeNode <int> >     newLinkedList      = new SinglyLinkedList <BinaryTreeNode <int> >();

                while (lastLinkedListNode != null)
                {
                    if (lastLinkedListNode.Data.Left != null)
                    {
                        // Add the left child to the linked list
                        newLinkedList.AppendToEnd(lastLinkedListNode.Data.Left);
                    }
                    if (lastLinkedListNode.Data.Right != null)
                    {
                        // Add the right child to the linked list
                        newLinkedList.AppendToEnd(lastLinkedListNode.Data.Right);
                    }

                    lastLinkedListNode = lastLinkedListNode.NextNode;
                }
                retList.Add(lastLinkedList);
                lastLinkedList = newLinkedList;
            }

            return(retList);
        }