Chinaunix首页 | 论坛 | 博客
  • 博客访问: 102013
  • 博文数量: 2
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 235
  • 用 户 组: 普通用户
  • 注册时间: 2006-08-15 07:02
文章存档

2011年(1)

2009年(1)

我的朋友

分类:

2009-03-11 23:36:21


#include
#include "bintree.cc"

using namespace std;
int pre_seq[]={2,4,7,6,3,1,5};
int in_seq[]={4,7,6,2,1,5,3};

/*

给定前序(前根)遍历序列 pre_seq 和中序(中根)遍历序列in_seq,

重构这个长得很怂的二插树。

         2
        / \
       /   \
       4    3
        \   /
         7 1
          \ \
           6 5
*/


// 前序序列索引,用以依次取出各层子树的根

static int pre_seq_index=0;


// isi_left: inorder sequence index left boundary
// isi_right: inorder sequence index right boundary
BinTreeNode<int> *BuildTree(int isi_left, int isi_right)
{
    
    if(isi_left>isi_right) return NULL;
    int root_value=pre_seq[pre_seq_index];
    pre_seq_index++;
    
    BinTreeNode<int>* node=new BinTreeNode<int>(root_value);
    if(isi_left==isi_right)
    {
        return node;
    }
 
    int i;
    for(i=isi_left; in_seq[i]!=root_value; i++);
    
    node->_left=BuildTree(isi_left, i-1);
    node->_right=BuildTree(i+1, isi_right);
  
    return node;
}

int main()
{
    BinTree<int> new_tree(BuildTree(0,6));
    cout<<"Tree reconstructed PreOrder:"<<endl;
    new_tree.PreOrder();
    cout<<endl;
    cout<<"Tree reconstructed InOrder:"<<endl;
    new_tree.InOrder();
    cout<<endl;

}


输出结果为:

Tree reconstructed PreOrder:
2 4 7 6 3 1 5
Tree reconstructed InOrder:
4 7 6 2 1 5 3

阅读(2405) | 评论(1) | 转发(0) |
0

上一篇:没有了

下一篇:博客已升级,请注意变更地址

给主人留下些什么吧!~~

chinaunix网友2009-03-12 02:01:52

同理,给定中根、后根遍历也是可以重构二叉树的。 有同学问“若给定前根、后根序列要如何重构?”, 其实这时候无法重构唯一的二叉树,因为前根、后根序列均只能对二叉树的深度次序作出描述,而无法描述子树的左右关系。比如 1 / 2 / \ 4 5 和 1 \ 2 / \ 4 5 这两棵树都有相同的前根,后根序列,但却是不同的树。