设为首页 加入收藏

TOP

已知中序后序创建二叉树
2014-11-24 10:59:59 】 浏览:8625
Tags:已知 后序 创建

 
#include
  
   
#include
   
     #include
    
      #include
     
       template
      
        class BinaryTree { public: struct TreeNode { Type data; TreeNode *leftchild, *rightchild; }; BinaryTree() {} ~BinaryTree(){} private: TreeNode *root; static TreeNode *_BuyNode() { TreeNode *p = (TreeNode *)malloc(sizeof(TreeNode)); assert(p != NULL); return p; } static int find(Type *is, const Type &x, int n) { for(int i = 0; i < n; ++i) { if(is[i] == x) return i; } return -1; } static TreeNode *CreatInPost(Type *post, Type *is, int n) { if(post == NULL || is == NULL || n ==0) return NULL; else { TreeNode *s = _BuyNode(); s->data = post[n-1]; int num = find(is, post[n-1], n); if(num == -1) exit(1); s->leftchild = CreatInPost(post, is,num);//此处放进去的是线序遍历的前num个 s->rightchild = CreatInPost(post+num, is+num +1, n-num-1);//此处减1是因为这是从后序遍历中找的每次最后一个数就被使用了,每次到这里就要将它除掉 return s; } } static void PreOrder(TreeNode *root) { if(root != NULL) { cout << root->data << " "; PreOrder(root->leftchild); PreOrder(root->rightchild); } } public: void Creat(Type *post, Type *is, int n) { if(post != NULL && is != NULL) root = CreatInPost(post, is, n); } void PreOrder() { PreOrder(root); cout << endl; } }; int main(void) { BinaryTree
       
         tree; int post[] = {34,56,67,45,23,89,78,12}; int is[] = {34,23,56,45,67,12,78,89}; int n = sizeof(post) / sizeof(post[0]); tree.Creat(post, is, n); tree.PreOrder(); return 0; }
       
      
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇HDU - 1175 连连看 下一篇题目1002:Grading

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目