0

i have this question : implement function int countSingle(), which uses Breadth-First Traversal (BFT) in order to count how many nodes in the tree have a single child.

so the code below is what i thought of to solve it , is there another way of doing this or a more efficient that i missed ?

template <class T>
        int BST<T>::countSingle()
        {
            QueueDLL<BSTNode<T>*> queue;
            BSTNode<T>* node = root;

            // If the tree is empty, there will be no nodes to traverse.
            if(node == NULL) return -1;

            // Initially, put the root in the queue
            queue.Enqueue(node);
            int counter = 0 ;

            while(queue.IsEmpty() == false)
            {
                // Take a node out of the queue, process it and then insert
                // its children into the queue.
                node = queue.Dequeue();

                // if the node has one only one child wether its the left or the right , increase counter
                if((node->left == NULL && node->right != NULL) || (node->right== NULL && node->left!=NULL))
                    counter++;

                if(node->left != NULL)
                    queue.Enqueue(node->left);
                if(node->right != NULL)
                    queue.Enqueue(node->right);
            }
            return counter;
        }

1 Answers1

0

This seems pretty much OK. You can't really improve the complexity of what you did, since the number of operations is linear.

A few implementation points:

  • Counting is a non-modifying operation, so you might want to consider consting some stuff.

  • You've basically implemented on your own something similar to what the compiler would do in recursion. If that's the intent - great (and there are some performance points in your favor). FYI, you could do this using recursion with very few LOCs.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • i think that would be a Preorder DFT which can be made using recursion but implemented using queue and this way its not recursion , i am not sure how i would go about this to make it in recursion tho – PyroStreak May 30 '15 at 19:46