BFS in binary tree

前端 未结 3 1491
我在风中等你
我在风中等你 2021-02-10 10:38

I\'m trying to write the codes for breadth-first search in binary tree. I\'ve stored all the data in a queue, but I can\'t figure out how to travel to all nodes and consume all

3条回答
  •  一向
    一向 (楼主)
    2021-02-10 10:48

    You are not doing a breadth first traversal here. Instead you are enqueuing the left and right element inside the queue and moving to the left subtree. You are exhausting the left subtree first and then moving on to the right subtree.

    Write a procedure to enqueue the node instead.

    void breadthFirstSearch (btree *bt, queue **q) {
     btree *tmpNode;
     enqueue(q,bt); //Assuming your root node has data
    
     while (!isempty(q)) //Assume isempty returns false when queue is not empty
     {
      tmpNode = dequeue(q);
      //Do whatever you want to do with tmpNode->data
      enqueue(tmpNode->left);
      enqueue(tmpNode->right);
      /* If this is a acyclic graph(tree) then this procedure should do, else you have to mark the nodes you have visited in-order not to end in a cycle */
     }
    
    }
    
    int main()
    {
    breadthFirstSearch(bt,q)
    return 0
    }
    

提交回复
热议问题