数据结构: 二叉树的建立与遍历源代码( 用c++ STL 实现)

本文介绍了二叉树的四种遍历方法:前序、中序、后序及层次遍历,并提供了使用栈和队列实现的具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ContractedBlock.gif ExpandedBlockStart.gif Code
#include "stdafx.h"
#include 
"binaryTree.h"
#include
<list>
#include
<vector>
#include
<stack>
#include
<queue>
using namespace std;

Status PreOrderTraverse(BiTree T, Status (
*Visit)(TElemType e))
{
    
if(IsEmpty(T))
        
return Ok;
/*
    Visit(T->data);
    PreOrderTraverse(T->lchild, Visit);
    PreOrderTraverse(T->rchild, Visit);
*/
    stack
<BiTNode *> stack;
    BiTNode
* t;
    stack.push(T);
    
while(!stack.empty())
    {
        t 
= stack.top();
        stack.pop();
        
if(t->rchild != null)
            stack.push(t
->rchild);
        Visit(t
->data);
        
if(t->lchild != null)
            stack.push(t
->lchild);
    }
    
return Ok;
}

Status InOrderTraverse(BiTree T, Status (
*Visit)(TElemType e))
{
    
if(IsEmpty(T))
        
return Ok;
    
    stack
<BiTNode *> stack;
    BiTNode
* t;
    stack.push(T);
    t 
= T->lchild;
    
while(!stack.empty())
    {
        
while(t != null)
        {
            stack.push(t);
            t 
= t->lchild;
        }
        t 
= stack.top();
        Visit(t
->data);
        stack.pop();
        t 
= t->rchild;
    }

    
return Ok;
}

Status PostOrderTraverse(BiTree T, Status (
*Visit)(TElemType e))
{
    
if(IsEmpty(T))
        
return Ok;
    
    stack
<BiTNode *> stack;
    BiTNode
* t;
    BiTNode
* pre = null;
    t 
= T;
    
while(!stack.empty() || t != null)
    {
        
while(t != null)
        {
            stack.push(t);
            t 
= t->lchild;
        }
        t 
= stack.top();
        
if(t->rchild == null || t->rchild == pre )
        {
            Visit(t
->data);
            stack.pop();
            pre 
= t;
            t 
= null;
        }
        
else
        {
            t 
= t->rchild;
        }
    }

    
return Ok;
}

Status LevelTraverse(BiTree T, Status (
*Visit)(TElemType e))
{
    queue
<BiTNode *> l;
    BiTNode
* t;
    l.push(T);
    
while(!l.empty())
    {
        t 
= l.front();
        
if(t->lchild != null)
            l.push(t
->lchild);
        
if(t->rchild != null)
            l.push(t
->rchild);
        Visit(t
->data);
        l.pop();
    }
    
return Ok;
}
以上是遍历的代码. 完整代码在 数据结构-稀疏矩阵和树的程序里.

转载于:https://www.cnblogs.com/froster/archive/2009/05/17/1458839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值