树的中序遍历

中序遍历按照“左孩子-根结点-右孩子”的顺序进行访问。

1.递归实现

void inOrder(BinTree* root)

{

  if(root!=NULL)

  {

    inOrder(root->lchild);

    cout<<root->data;

    inOrder(root->rchild);

  }

}

 

2.非递归实现

 对于任一结点P,

  1)若其左孩子不为空,则将P入栈并将P的左孩子置为当前的P,然后对当前结点P再进行相同的处理;

  2)若其左孩子为空,则取栈顶元素并进行出栈操作,访问该栈顶结点,然后将当前的P置为栈顶结点的右孩子;

  3)直到P为NULL并且栈为空则遍历结束

void inOrder(BinTree* root)

{

  stack<BinTree*> s;

  BinTree* p=root;

  while(p!=NULL || !s.emtpy())

  {

    while(p!=NULL)

    {

      s.push(p);

      p=p->lchild;

    }

    if(!s.empty())

    {

      p=s.top();

      s.pop();      

      cout<<p->data;

      p=p->rchild;      

    }

  }

  

}

 

posted @ 2015-04-16 17:45  hy1hy  阅读(141)  评论(0编辑  收藏  举报