二叉树重建

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<&& 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.     }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值