二叉樹的中序遍歷序列和后序遍歷序列,按層遍歷序列該二叉樹

C++實現

#include <iostream>
#include <queue>
using namespace std;
class Tree
{
public:
  Tree(char *in, char *post, int len);
  char data;
  Tree *Lchild;
  Tree *Rchild;
  void LevelReverse(int (*func)(int ch));
};
Tree::Tree(char *in, char *post, int len)
{
  Lchild = Rchild = NULL;
  data = post[len - 1];
  if (len > 1)
  {
      int i = 0;
      while (in[i] != data) 
    {
         i++;
    }
      if (i > 0)
    {
         Lchild = new Tree(in, post, i);
        
    }
      if (len - 1 - i > 0) 
    {
         Rchild = new Tree(in + i + 1, post + i, len - i - 1);
       
    }
  }
}
void Tree::LevelReverse(int (*func)(int ch))
{
    //通過隊列,用廣搜實現按層遍歷
      queue<Tree *>
          treeQueue;
  func(data);
  treeQueue.push(this);
  while (!treeQueue.empty())
  {
      if (treeQueue.front()->Lchild)
    {
         func(treeQueue.front()->Lchild->data);
         treeQueue.push(treeQueue.front()->Lchild);
    }
      if (treeQueue.front()->Rchild)
    {
         func(treeQueue.front()->Rchild->data);
         treeQueue.push(treeQueue.front()->Rchild);
    }
      treeQueue.pop();
  }
}
int main()
{
  char in[1000], post[1000];
  gets(in);
  gets(post);
  Tree root(in, post, strlen(in));
  root.LevelReverse(putchar);
  putchar('\n');
  return 0;
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容