中序遍歷二叉樹

創建一個二叉樹,並實現對二叉樹的中序遍歷。

這裏用兩種方法實現對二叉樹的中序遍歷:第一種方法:遞歸方法,該方法不需要使用輔助工具棧;

                                                                             第二種方法:非遞歸方法,該方法需要使用棧。

下面是具體實現:

treenode.h

struct BinaryTreenode
{
 int mvalue;
 BinaryTreenode *pleft;
 BinaryTreenode *pright;
};

 

 

#include <iostream>
#include <stack>
#include "treenode.h"
using namespace std;

BinaryTreeNode *creatTree(unsigned int n);
void inorder(BinaryTreeNode *proot);

int main()
{
 BinaryTreeNode *proot=creatTree(10);
 inorder(proot);

 return 0;
}

 

//創建二叉樹

BinaryTreeNode *creatTree(unsigned int n)
{
 if (n<=0)
 {
  cout <<"ERROR!" <<endl;
  return NULL;
 }
 BinaryTreeNode *proot=NULL;
 BinaryTreeNode *v[20]={NULL};

 int i=0,j=0;
 int val;
 while(i<n)
 {
  cin >>val;
  BinaryTreeNode *pnode=new BinaryTreeNode();
  pnode->m_val=val;
  pnode->pleft=NULL;
  pnode->pright=NULL;

  v[i]=pnode;
  if (i==0)
  {
   proot=pnode;
  }
  else
  {
   j=(i+1)/2;
   if (i&1==1)
   {
    v[j-1]->pleft=pnode;
   }
   else
   {
    v[j-1]->pright=pnode;
   }
  }
  i++;
 }
 return proot;
}

/*
//遞歸實現中序遍歷
void inorder(BinaryTreeNode *proot)
{
 if (proot==NULL)
 {
  return;
 }

 if(proot)
 {
  inorder(proot->pleft);
  printf("%d ",proot->m_val);
  inorder(proot->pright);
 }
}
*/

//非遞歸實現中序遍歷
void inorder(BinaryTreeNode *proot)
{
 if (proot==NULL)
 {
  return;
 }

 stack<BinaryTreeNode *> st;
 while(proot || !st.empty())
 {
  while(proot)
  {
   st.push(proot);
   proot=proot->pleft;
  }
  if (st.size()!=0)
  {
   proot=st.top();
   printf("%d ",proot->m_val);
   proot=proot->pright;
   st.pop();
  }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章