美文网首页
二叉树的中序遍历序列和后序遍历序列,按层遍历序列该二叉树

二叉树的中序遍历序列和后序遍历序列,按层遍历序列该二叉树

作者: SummerC0ld | 来源:发表于2017-04-06 15:21 被阅读0次

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;
}

相关文章

  • 先序,中序序列 推导后序序列

    Problem Description 输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。 In...

  • 数据结构与算法二叉树的遍历与线索二叉树以及森林

    1.二叉树的遍历先序遍历、中序遍历、后序遍历 2.层次遍历利用队列实现 3.由遍历序列构成二叉树先序、后序可以与众...

  • 二叉树的遍历

    本节主要介绍如何根据二叉树的遍历序列还原二叉树 1.根据前序遍历序列ABCDEF和中序遍历序列CBAEDF如何判断...

  • 重建二叉树 - 利用后序遍历与中序遍历C++实现

    重建二叉树 引言 问题:现有二叉树的后序遍历序列与中序遍历序列,能否求原二叉树? 答案是肯定的,并且前序与中序也可...

  • leetCode进阶算法题+解析(十六)

    从中序和后序遍历序列构造二叉树 题目:根据一棵树的中序遍历与后序遍历构造二叉树。 注意:你可以假设树中没有重复的元...

  • 二叉树-3

    今天解决了人生导师留给我的第一个问题——通过前序遍历和中序遍历序列,求解后序遍历序列。 思路:D&C 对于二叉树,...

  • 中序和后序遍历建立二叉树

    106. 从中序与后序遍历序列构造二叉树 根据一棵树的中序遍历与后序遍历构造二叉树。 注意:你可以假设树中没有重复...

  • 106.从中序与后序遍历序列构造二叉树

    题目#106.从中序与后序遍历序列构造二叉树 根据一棵树的中序遍历与后序遍历构造二叉树。 注意:你可以假设树中没有...

  • 重建二叉树

    输入二叉树的前序遍历序列和中序遍历序列,重建此二叉树。 public class RebuildTree { cl...

  • 二叉树考虑空节点的遍历

    通常我们进行二叉树的遍历(前序遍历、中序遍历和后序遍历)时,不考虑空节点。但有时需要我们将空节点也放入遍历序列中。...

网友评论

      本文标题:二叉树的中序遍历序列和后序遍历序列,按层遍历序列该二叉树

      本文链接:https://www.haomeiwen.com/subject/golqattx.html