0
votes

I understand the logic of using a queue to visit the nodes in a binary search tree level by level. However i tried to implemment in C but i'am stuck because i don't know how to enqueue them properly. Starting with the root i can create a Queue but after that if i add the children of the root to the queue i will lose the children of those new nodes since iam modifying the connections in the Queue every time a add a new node.

I could create a new data type that has one more link to use in the linked list Queue, that should work. What is the best approach here?

1
Use a linked list as the container for a queue. And please read a good elementary book, as it will be covered in detail there.therainmaker
BSTs and Queues are both abstract data types. you don't use a Queue to create a BST.ForeverStudent

1 Answers

1
votes

visit[ing] the nodes in a binary search tree level by level

has a name: it is called a "breadth-first" traversal of the tree. Starting with an empty queue, you enqueue the root node and then repeatedly dequeue the first node in the queue, process it somehow, and enqueue all that node's children, until there are no more nodes enqueued. When exactly you should enqueue a node's children relative to other processing of that node may depend on exactly what processing you intend to perform, especially if it involves structurally modifying the tree.

As long as the per-node processing can affect only the subtree rooted at the then-current node, this is all fine. If you need to be able to affect other parts of the overall tree, however, then a breadth-first traversal probably is not appropriate for your task.

You said

[I] don't know how to enqueue them properly. Starting with the root [I] can create a Queue but after that if [I] add the children of the root to the queue [I] will lose the children of those new nodes since [I] am modifying the connections in the Queue every time a add a new node.

The key concept here is that membership and position in the queue are separate and independent from membership and position in the tree. You could manage that by adding additional links to the node structures themselves, or by creating a new structure for the queue elements that contains a pointer to the enqueued BST node. The latter decouples the tree from the queue, which many, including me, would consider preferable for most purposes.