【问题标题】:Level-order traversal of a binary tree二叉树的层序遍历
【发布时间】:2013-03-01 20:47:39
【问题描述】:

我想执行二叉树的级别顺序遍历。因此,对于给定的树,说:

     3
    / \
   2   1
  / \   \
 4   6   10

输出将是:

3 2 1 4 6 10

我知道我可以使用某种队列,但是在 C 中递归执行此操作的算法是什么?任何帮助表示赞赏。

【问题讨论】:

    标签: c algorithm binary-tree


    【解决方案1】:

    图算法称为广度优先搜索,它使用队列进行层序遍历,这里是伪代码

    void breadth_first(Node root)
    {
      Queue q;
      q.push(root);
      breadth_first_recursive(q)
    }
    
    void breadth_first_recursive(Queue q)
    {
      if q.empty() return;
      Node node = q.pop()
      print Node
      if (n.left) q.push(n.left)
      if (n.right) q.push(n.right)
      breadth_first_recursive(q)
    }
    

    【讨论】:

    • 我明白这一点,我要求算法在没有循环的情况下递归地执行此操作。
    • 好的,我要发布一个递归示例,给我一点时间
    • 谢谢,我想我可以用我拥有的 que 系统很容易地实现这一点。
    【解决方案2】:

    这里是来自维基百科的伪代码

    levelorder(root)
      q = empty queue
      q.enqueue(root)
      while not q.empty do
        node := q.dequeue()
        visit(node)
        if node.left ≠ null
        q.enqueue(node.left)
        if node.right ≠ null
        q.enqueue(node.right)
    

    然后您可以将其转换为微不足道的 C...

    【讨论】:

    【解决方案3】:

    此处代码(无递归函数)来自 C5 库:C5 UserGuideExamples - TreeTraversal

    public static void BreadthFirst(Tree<T> t, Action<T> action)
    {
      IQueue<Tree<T>> work = new CircularQueue<Tree<T>>();
      work.Enqueue(t);
      while (!work.IsEmpty)
      {
        Tree<T> cur = work.Dequeue();
        if (cur != null)
        {
          work.Enqueue(cur.t1);
          work.Enqueue(cur.t2);
          action(cur.val);
        }
      }
    }
    

    【讨论】:

      【解决方案4】:

      另一种非递归方法..

      void LevelOrder(node * root)
      {
        queue<node *> q;
          node *n=new node;
          n=root;
          while(n)
          {
              cout<<n->data<<" ";
              if(n->left)
                  q.push(n->left);
              if(n->right)
                  q.push(n->right);
              n=q.front();
              q.pop();
      
      
          }
      
      
      
      }
      

      【讨论】:

        【解决方案5】:
        void    levelorder    (Node *root)
        {
           if(!root)
               return;
           queue<Node*>    Q;
           Q.push(root);
           while(!Q.empty())
           {
            Node *current   =    Q.front();//returns the front element in queue
            cout <<current->data;//printing the front node of queue
            if(current->left!=NULL)
              Q.push(current->left);//pushing left child
            if(current->right!=NULL)
              Q.push(current->right);//pushing right child
             Q.pop();//removing front element from queue.
           }
        }
        

        【讨论】:

        • 这是 c++ 代码,我在头文件 #include 下使用了 c++ 中可用的 inblit 队列
        【解决方案6】:

        在C语言中,基本队列可以通过栈使用,即数组

        #include<stdio.h>
        
        #include<stdlib.h>
        
        #define MaxSize 10
        
        //typedef char ElemType;
        typedef int ElemType;
        typedef struct BiTNode {
            ElemType data;
            struct BiTNode * lchild, * rchild;
        }
        BiTNode, * BiTree;
        
        void BuildTree(BiTree * T) {
            /*
                                    t1
                            t2              t3
                        t4       t5              t6
        
            */
            BiTNode * t1 = T;
            t1 -> data = 3;
        
            BiTree t2 = (BiTNode * ) malloc(sizeof(BiTNode));
            t2 -> data = 2;
            t1 -> lchild = t2;
        
            BiTree t3 = (BiTNode * ) malloc(sizeof(BiTNode));
            t3 -> data = 1;
            t1 -> rchild = t3;
        
            BiTree t4 = (BiTNode * ) malloc(sizeof(BiTNode));
            t4 -> data = 4;
        
            BiTree t5 = (BiTNode * ) malloc(sizeof(BiTNode));
            t5 -> data = 6;
            t2 -> lchild = t4;
            t2 -> rchild = t5;
        
            BiTree t6 = (BiTNode * ) malloc(sizeof(BiTNode));
            t6 -> data = 10;
            t3 -> rchild = t6;
        
            t3 -> lchild = NULL;
            t4 -> lchild = NULL;
            t4 -> rchild = NULL;
            t5 -> lchild = NULL;
            t5 -> rchild = NULL;
            t6 -> lchild = NULL;
            t6 -> rchild = NULL;
        }
        void print2DUtil(struct BiTNode * root, int space) {
            // Base case
            if (root == NULL)
                return;
        
            // Increase distance between levels
            space += MaxSize;
        
            // Process right child first
            print2DUtil(root -> rchild, space);
        
            // Print current node after space
            // count
            printf("\n");
            for (int i = MaxSize; i < space; i++)
                printf(" ");
            printf("%d\n", root -> data);
        
            // Process left child
            print2DUtil(root -> lchild, space);
        }
        // Wrapper over print2DUtil()
        void PrintTree(struct BiTNode * root) {
            // Pass initial space count as 0
            print2DUtil(root, 0);
        }
        void visit(BiTree T) {
            printf("%d  ", T -> data);
        }
        //BFS
        void BFS(BiTree T) {
            if (T != NULL) {
                int front = 0;
                int rear = 0;
                BiTree queue[MaxSize];
                BiTree p;
                p = T;
                rear = (rear + 1) % MaxSize;
                queue[rear] = p;
                while (rear != front) {
                    front = (front + 1) % MaxSize;
                    p = queue[front];
                    visit(p);
                    if (p -> lchild != NULL) {
                        rear = (rear + 1) % MaxSize;
                        queue[rear] = p -> lchild;
                    }
                    if (p -> rchild != NULL) {
                        rear = (rear + 1) % MaxSize;
                        queue[rear] = p -> rchild;
                    }
        
                }
            }
        }
        
        void DelTree(BiTree T) {
            if (T == NULL) return;
            DelTree(T -> lchild);
            DelTree(T -> rchild);
            free(T);
        }
        
        int main() {
            BiTree t = (BiTNode * ) malloc(sizeof(BiTNode));
            printf("Tree:");
            BuildTree(t);
            PrintTree(t);
            printf("\n");
            printf("BFS:");
            BFS(t);
            printf("\n");
        
            DelTree(t);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-08
          • 2020-01-15
          • 1970-01-01
          • 2023-01-09
          • 2016-04-16
          • 2012-01-01
          相关资源
          最近更新 更多