计数BST中具有单个子节点的节点

Counting Nodes with single child in BST

本文关键字:子节点 节点 单个 BST 计数      更新时间:2023-10-16

我有这个问题:实现函数int countSingle(),它使用宽度优先遍历(BFT)来计算树中有多少节点有一个子节点。

所以下面的代码是我想到的解决它的方法,有没有另一种方法或者我错过的更有效的方法?

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;
        }

这看起来很好。你不能真正提高你所做的事情的复杂性,因为操作的数量是线性的。

几个实现要点:

  • 计数是一个不可修改的操作,所以你可能要考虑const一些东西

  • 你基本上已经实现了类似于编译器在递归中所做的事情。如果这是你的意图,那就太好了(还有一些性能点对你有利)。仅供参考,您可以使用极少loc的递归来完成此操作。