码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 根据前序遍历序列和中序遍历序列可以构造唯一的二叉树

时间:2014-11-08 16:47:32      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:二叉树   递归   遍历   

文章转载自http://blog.csdn.net/touzani/article/details/1637195

根据前序遍历序列和中序遍历序列可以构造唯一的二叉树。

假设序列为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

C++ 根据前序遍历序列和中序遍历序列可以构造唯一的二叉树

标签:二叉树   递归   遍历   

原文地址:http://blog.csdn.net/u014492257/article/details/40921615

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!