您的位置:首页 > 理论基础 > 数据结构算法

分层遍历二叉树

2011-05-23 17:37 316 查看
1.递归的做法:

把输出二叉树第K层结点转换成:分别输出”以该二叉树根结点的左右子树为根的两棵子树”中第K-1层结点。(降维法)

void PrintNodeAtLevel(Node *root , int level)
{
    if(!root || level < 0)
        return ;
    if(level == 0)
    {
        printf(“%c”, root->chValue);
    }
    else{

           PrintNodeAtLevel(root->lChild , level – 1);
           PrintNodeAtLevel(root->rChild , level – 1);  }
}

 

 

 

 

2.广度优先搜索(BFS)

用到了典型数据结构–队列。BFS不是递归算法。

void InitQueue()
{
    front = rear = 0;
}

void EnQueue(Node *p)
{
    Q[rear++] = p;
}

Node *DeQueue()
{
    return Q[front++];
}                                                 //以上定义了队列这一数据结构

void PrintNodeByLevel(Node *root)
{
    int last;
    Node *p;

    if(!root)    return ;

    InitQueue();
    EnQueue(root);
    while(front < rear)
    {
        last = rear;                                                   last指向某一层(分层遍历)的结束
        while(front < last)            
        {
            p = DeQueue();
            printf(“%c”, p->chValue);
            if(p->lChild)    EnQueue(p->lChild);
            if(p->rChild)    EnQueue(p->rChild);               入队后rear变了!!
        }
        printf(“/n”);                //某一层遍历完之后换行
    }
}

 

 

 

 

 

法二:

void PrintNodeByLevel(Node* root) { 
queue<Node*> Q; 
Q.push(root); 
Q.push(0);      //初始化,只输入根节点,并且置该层结束符NULL
do { 
         Node* node = Q.front(); 
         Q.pop(); 
         if (node) {                                 //若取到的是某一层的节点
             cout << node->data << ” “; 
             if (node->pLeft) 
                 Q.push(node->pLeft); 
             if (node->pRight) 
                 Q.push(node->pRight); 
                   } 

          else if (!Q.empty()&&!node)    //若取到了该层结束符NULL且队列非空,则表示该层结束,相应的该层对应的下一层已经全部入队,所以置一个下层结束符NULL,并且回车
          { 
             Q.push(0); 
             cout << endl; 
            } 
      } while (!Q.empty()); 
 }

 

 

 

sited from http://www.cnblogs.com/miloyip/archive/2010/05/12/binary_tree_traversal.html

http://www.cnblogs.com/DiaoCow/archive/2010/06/01/1749187.html

并做了改动和注释
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息