数据结构--二叉树遍历 C++实现

来源:互联网 发布:比邻交友软件 编辑:程序博客网 时间:2024/06/05 20:55

1、二叉树结构定义

struct node{

  int data;//数据

 node * leftchild;//左孩子结点

node * rightchild;//右孩子结点

}

2、二叉树的递归遍历

   2.1先序遍历

       void preorder(node *r){

     if(r!=NULL){//NULL 还是null?

       cout<<r->data<<endl;//访问结点

       preorder(r->leftchild);//递归访问左结点

      preorder(r->rightchild);//递归访问右结点

       }

    }

   2.2中序遍历

   void inorder(node *r){

     if(r!=NULL){

     inorder(r->leftchild);

    cout<<r->data<<endl;

    inorder(r->rightchild);

   }

}

   2.3后序遍历

void postorder(node *r){

  if(r!=NULL){

   postorder(r->leftchild);

   postorder(r->rightchild);

   cout<<r->data<<endl;

}

}

3、二叉树的非递归遍历(中序遍历)

  思路:设S为一个工作栈,P为指向根结点的指针;

        【1】当P为非空时,将P指向的结点进栈,并将P指向该结点的左子树;

        【2】当P为空时,弹出栈顶元素,显示结点元素,并将P指向该结点的右子树;(相当于左子树已经访问完,访问结点,然后访问右子树)

        【3】重复步骤【1】【2】,直到栈为空,P为空。

实现:

     void InOder(node * r)

{

stack<node *> S;

node *P;

P=r;

while(P||!S.IsEmpty())

{

    if(p)

     {

     S.push(P);

     P=P->leftchild;

     }

   else

  {

  S.pop();

   cout<<p->data<<endl;

   P=P->rightchild;

   }

}

}

 

0 0