重建二叉树
2016-05-13 13:48
302 查看
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树,假设输入的前序遍历和中序遍历的结果中都不含重复的数字,例如输入前序遍历{ 1,2, 4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}则重建出图2.6所示的二叉树并输出它的头结点。
#pragma once #include<queue> struct BTNode { int value; BTNode* left; BTNode* right; }; BTNode* ConstructCore(int * startPrevorder, int* endPreorder , int* startInorder , int* endInorder) { int rootValue = startPrevorder [0]; BTNode *root = new BTNode(); root->value = rootValue; root->left = root->right = NULL; if (startPrevorder == endPreorder) { if (startInorder == endInorder &&* startPrevorder == *startInorder ) return root; else throw std::exception ("Invalid input."); } int* rootInorder = startInorder ; while (rootInorder <= endInorder &&*rootInorder != rootValue) ++rootInorder; if (rootInorder == endInorder &&*rootInorder != rootValue) throw std::exception ("Invalid input."); int leftLength = rootInorder - startInorder ; int* leftPreorderEnd = startPrevorder + leftLength; if (leftLength > 0) { root->left = ConstructCore( startPrevorder + 1, leftPreorderEnd, startInorder, rootInorder - 1); } if (leftLength < endPreorder - startPrevorder) { root->right = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder ); } return root; } BTNode* Construct(int * prevorder, int* inorder , int length) { if (prevorder == NULL || inorder == NULL || length <= 0) return NULL ; return ConstructCore(prevorder , prevorder + length - 1, inorder, inorder + length - 1); } void Test() { int pre[8] = { 1, 2, 4, 7, 3, 5, 6, 8 }; int in[8] = { 4, 7, 2, 1, 5, 3, 8, 6 }; BTNode* root = Construct(pre, in, 8); //PrintTree(root); }
相关文章推荐
- 使用 itext、flying-saucer 实现html转PDF
- 【操作系统】实验三 进程调度模拟程序
- 用户场景
- android开发之synchronized的用法
- 优化Privoxy的打开和关闭
- OpenResty反爬虫
- 01.C++ STL简介
- 直接双击启动tomcat中的startup.bat闪退原因及解决方法
- 进程描述和控制
- 20个正则表达式
- HashTable
- Java swing简单记事本
- WPF 学习资料收集 学习路径
- 深究AngularJS——校验(非form表单)
- 转发重定向的区别
- Unity3D 网络通信_HTTP协议:获取网络图片、内容
- 高效开发Android App的10个建议
- Uva 796 Critical Links 找桥
- springMVC两种方式实现多文件上传及效率比较
- js跳转页面