c++ - Counting Nodes with single child in BST -
i have question : implement function int countsingle(), uses breadth-first traversal (bft) in order count how many nodes in tree have single child.
so code below thought of solve , there way of doing or more efficient missed ?
template <class t> int bst<t>::countsingle() { queuedll<bstnode<t>*> queue; bstnode<t>* node = root; // if tree empty, there no nodes traverse. if(node == null) return -1; // initially, put root in queue queue.enqueue(node); int counter = 0 ; while(queue.isempty() == false) { // take node out of queue, process , insert // children queue. node = queue.dequeue(); // if node has 1 1 child wether left or 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; }
this seems pretty ok. can't improve complexity of did, since number of operations linear.
a few implementation points:
counting non-modifying operation, might want consider
consting stuff.you've implemented on own similar compiler in recursion. if that's intent - great (and there performance points in favor). fyi, using recursion few locs.
Comments
Post a Comment