您的位置:首页 > 其它

根据前序和中序序列重建二叉树

2013-01-30 23:44 295 查看
http://blog.chinaunix.net/uid-1844931-id-3033009.html

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

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 ,我们就可以递归的把左子树给建立起来。 同样,可以建立起右子树。

下面是写的伪代码,(没有编译过)

class TreeNode

{

pubic:

char value;

TreeNode *left;

TreeNode *right;

TreeNode(char c): value(c){

left = NULL;

rigth = NULL;

}

~TreeNode() {

if(left != NULL) delete left;

if(right != NULL) delete right;

}

};

/**根据前序周游和中序周游,重建一颗二叉树。

* @param pre 前序周游的结果,其中每一个字符表示一个节点的值

* @param mid 中序周游的结果,其中每一个字符表示一个节点的值

* @param n 该树节点总数。

* @return 生成的树的根节点。

*/

TreeNode* buildTree(char *pre, char *mid, int n)

{

if (n==0) return NULL;

char c = pre[0];

TreeNode *node = new TreeNode(c); //This
is the root node of this tree/sub tree.

for(int i=0; i<n && mid[i]!=c; i++);

int lenL = i; // the node number
of the left child tree.

int lenR = n - i -1; //
the node number of the rigth child tree.

//build the left child tree. The first order for thr left child tree is from

// starts from pre[1], since the first element in pre order sequence is the root

// node. The length of left tree is lenL.

if(lenL > 0) node->left = buildTree(&pre[1], &mid[0], lenL);

//build the right child tree. The first order stree of right child is from

//lenL + 1(where 1 stands for the root node, and lenL is the length of the

// left child tree.)

if(lenR > 0) node->right = buildTree(&pre[lenL+1], &mid[lenL+1], lenR);

return node;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: