您的位置:首页 > 其它

根据前序遍历序列和中序遍历序列构造二叉树

2007-06-04 10:43 483 查看
根据前序遍历序列和中序遍历序列可以构造唯一的二叉树。
假设序列为string型
根据前序遍历的特点, 知前序序列(Pre)的首个元素(Pre[0])为根(root), 然后在中序序列(In)中查找此根(Pre[0]), 根据中序遍历特点, 知在查找到的根(root) 前边的序列为左子树, 后边的序列为右子树。 设根前边有left个元素.. 则又有, 在前序序列中, 紧跟着根(root)的left个元素序列(即Pre[1...left]) 为左子树, 在后边的为右子树..而构造左子树问题其实跟构造整个二叉树问题一样,只是此时前序序列为Pre[1...left]), 中序序列为In[0...left-1], 分别为原序列的子串, 构造右子树同样, 显然可以用递归方法解决。

因此算法可以描述为:
build_tree(sub_root, Pre, In)
1。if ( size( Pre) > 0)
2。 sub_root =new Node (Pre[0] );
3。 Index = Pre[0]在In中的位置
4。 In_left = In[0...Index-1] , In_right = In[Index...]
5。 Pre_left =Pre[1..Index], Pre_righ = Pre[Index+1...]
6。 build_tree(sub_root->left , Pre_left, In_left)
7。 build_tree(sub_root->right, Pre_right, Pre_right)

C++代码如下:

template <class Entry>


Binary_tree<Entry>::Binary_tree(string p, string s)




/**//* p是二叉树的先序序列,s是二叉树的中序序列。算法建立二叉树,使其先序序列和中序序列分别为p和s。


uses: pre_in_build


*/




...{


pre_in_build(root, p, s);


}


template <class Entry>


void Binary_tree<Entry>::pre_in_build(Binary_node<Entry> *&sub_root, string pre, string in)




...{




if(pre.length() > 0)




...{


sub_root=new Binary_node<char> (pre[0]);


int index=in.find(pre[0]);


string in_left_str=in.substr(0, index);


string in_right_str=in.substr(index+1);


string pre_left_str=pre.substr(1, index);


string pre_right_str=pre.substr(index+1);


pre_in_build(sub_root->left, pre_left_str, in_left_str);


pre_in_build(sub_root->right, pre_right_str, in_right_str);


}


}



string 类返回子串函数
basic_string substr( size_type _Off = 0, size_type _Count = npos )
参数说明:
_Off 为开始的下标, 默认为0。
_Count为子串的大小, 默认从开始到串的末尾。
npos = -1; 代表not found 或all remaining characters
返回子串string
如果_Count =0, 则返回为空的string
如果下标_Off >= length, 亦返回空string
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐