Chinaunix首页 | 论坛 | 博客
  • 博客访问: 651167
  • 博文数量: 45
  • 博客积分: 931
  • 博客等级: 准尉
  • 技术积分: 590
  • 用 户 组: 普通用户
  • 注册时间: 2005-04-17 13:27
文章分类

全部博文(45)

文章存档

2013年(6)

2012年(15)

2011年(23)

2005年(1)

分类: C/C++

2011-12-02 17:40:49

今天一个小朋友问到这个问题,顺便复习一下数据结构了。

PreOrder(T)=T的根节点+PreOrder(T的左子树)+PreOrder(T的右子树)
InOrder(T)=InOrder(T的左子树)+T的根节点+InOrder(T的右子树)
PostOrder(T)=PostOrder(T的左子树)+PostOrder(T的右子树)+T的根节点
其中加号表示字符串连接运算

例如,对下图所示的二叉树,先序遍历为DBACEGF,中序遍历为ABCDEFG。重建该二叉树:

这个算法其实很简单的。 首先你自己要能够根据先序和中序能够手动的建立起来树。 先序串:DBACEGF,先序的第一个节点一定是根节点,这样我们就知道了根节点是D. 再看中序, 在中序串之中,根结点的前边的所有节点都是左子树中,ABCDEFG,所以D节点前面的ABC就是左子树的中序串。再看前续串 DBACEGF, 由于左子树的节点是ABC,我们可以得到左子树的前续周游的串为: BAC. 有了左子树的前序串BAC,和中序串ABC ,我们就可以递归的把左子树给建立起来。 同样,可以建立起右子树。

下面是写的伪代码,(没有编译过)
  1. class TreeNode
  2. {
  3. pubic:
  4.     char value;
  5.     TreeNode *left;
  6.     TreeNode *right;
  7.     TreeNode(char c): value(c){
  8.         left = NULL;
  9.         rigth = NULL;
  10.     }
  11.     ~TreeNode() {
  12.         if(left != NULL) delete left;
  13.         if(right != NULL) delete right;
  14.     }
  15. };


  1.   /**根据前序周游和中序周游,重建一颗二叉树。
  2.    * @param pre 前序周游的结果,其中每一个字符表示一个节点的值
  3.    * @param mid 中序周游的结果,其中每一个字符表示一个节点的值
  4.    * @param n 该树节点总数。
  5.    * @return 生成的树的根节点。
  6.    */

  7.     TreeNode* buildTree(char *pre, char *mid, int n)
  8.     {
  9.         if (n==0) return NULL;
  10.         
  11.         char c = pre[0];
  12.         TreeNode *node = new TreeNode(c); //This is the root node of this tree/sub tree.
  13.         
  14.         for(int i=0; i<n && mid[i]!=c; i++);
  15.         int lenL = i; // the node number of the left child tree.
  16.         int lenR = n - i -1; // the node number of the rigth child tree.
  17.         
  18.         //build the left child tree. The first order for thr left child tree is from
  19.         // starts from pre[1], since the first element in pre order sequence is the root
  20.         // node. The length of left tree is lenL.
  21.         if(lenL > 0) node->left = buildTree(&pre[1], &mid[0], lenL);
  22.         //build the right child tree. The first order stree of right child is from
  23.         //lenL + 1(where 1 stands for the root node, and lenL is the length of the
  24.         // left child tree.)
  25.         if(lenR > 0) node->right = buildTree(&pre[lenL+1], &mid[lenL+1], lenR);
  26.         return node;
  27.     }


阅读(17432) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~