首页 > 代码库 > 广度优先遍历二叉树

广度优先遍历二叉树




// //广度优先遍历二叉树
// //从一个顶点开始,识别所有可到达顶点
// //的方法叫作广(宽)度优先搜索,这种
// //搜索可使用队列来实现

 typedef struct binarytree
 {
  EleType data;
  struct binarytree *LeftChild;
  struct binarytree *RightChild;
 }Tree; 
// 
 class Node
 {
  Tree t;
  Node next;
 };
// 
 class Queue
 {
  Node head;
  Node tail;
 public:
  void enque(Tree t)
  {
   Node n;
   n.t = t;
   if (!tail)
   {
    tail = head = n;
   }
   else
   {
    tail.next = n;
    tail = n;
   }
  }
  Tree deque()
  {
   if (!head)
   {
    return NULL;
   }
   else
   {
    Node n = head;
    head =  head.next;
    return n.t;
   }
  }
 };
// 
 void BST(Tree t)
 {
  Queue q;
  q.enque(t);
  Tree t = q.deque();
  while (t)
  {
   printf(t.data);
   if(t.LeftChild)
    q.enque(t.LeftChild);
   if(t.RightChild)
    q.enque(t.RightChild);
   t = q.deque();
  }
 }