剑指offer面试题6:重建二叉树
来源:互联网 发布:单片机培训网 编辑:程序博客网 时间:2024/06/03 19:55
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树,输出头结点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
struct BinaryTreeNode{ int m_nValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight;}
#include <exception>#include <iostream>#include <vector>using namespace std;struct BinaryTreeNode { int m_nValue; BinaryTreeNode *m_pLeft; BinaryTreeNode *m_pRight;};BinaryTreeNode *construct(const vector<int> &forward, int fs, int fe, const vector<int> &midward, int ms, int me) { //头结点为第一个元素 BinaryTreeNode *head = new BinaryTreeNode; head->m_nValue = forward[fs]; head->m_pLeft = head->m_pRight = NULL; if (fs == fe && ms == me) return head; //在中序遍历中找到根节点 int mid = ms; while (mid < me && midward[mid] != forward[fs]) ++mid; int leftfe = fs + mid - ms; if (mid > ms) head->m_pLeft = construct(forward, fs + 1, leftfe, midward, ms, mid - 1); if (mid < me) head->m_pRight = construct(forward, leftfe + 1, fe, midward, mid + 1, me); return head;}BinaryTreeNode *Reconstruct(const vector<int> &forward, const vector<int> &midward) { if (forward.empty() || midward.empty()) return NULL; return construct(forward, 0, forward.size() - 1, midward, 0, midward.size() - 1);}void printlist(BinaryTreeNode *head) { if (head == NULL) return; cout << head->m_nValue << " "; printlist(head->m_pLeft); printlist(head->m_pRight);}int main(int argc, char const *argv[]) { int ia[] = {1, 2, 4, 7, 3, 5, 6, 8}; vector<int> forward(ia, ia + 8); int ib[] = {4, 7, 2, 1, 5, 3, 8, 6}; vector<int> midward(ib, ib + 8); BinaryTreeNode *head = Reconstruct(forward, midward); printlist(head); return 0;}
0 0
- 《剑指Offer》面试题-重建二叉树
- 剑指offer--面试题6: 重建二叉树(树)
- 剑指offer-->面试题6 重建二叉树
- 【剑指offer】面试题6:重建二叉树
- 《剑指offer》面试题6:重建二叉树
- 剑指offer 面试题6 重建二叉树
- 剑指Offer:面试题6 重建二叉树
- 《剑指offer》面试题6:重建二叉树
- 《剑指offer》面试题6重建二叉树
- 剑指offer面试题6--重建二叉树
- 理解《剑指Offer》之面试题6 重建二叉树
- 剑指offer 面试题6 重建二叉树
- 剑指offer面试题6 重建二叉树(c)
- 剑指offer面试题6 重建二叉树(java)
- 《剑指Offer》面试题6:重建二叉树
- 剑指offer--面试题6:重建二叉树--Java实现
- 【剑指Offer学习】【面试题6 :重建二叉树】
- 《剑指Offer》学习笔记--面试题6:重建二叉树
- TI面试 销售岗和 AE岗
- java 使用JSqlParser 解析sql语句中的表字段
- Android-Universal-Image-Loader
- Subversion客户端远程修改用户密码配置Apache22Passwd
- PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载
- 剑指offer面试题6:重建二叉树
- git常用命令
- 情绪阀门
- 如何用mysql命令行模式导入sql文件
- LeetCode226. Invert Binary Tree
- C/C++中调用外部文件的函数时如何编写头文件
- Android应用开发性能优化完全分析
- VS 2010 的 Cannot find or open the PDB file发生的可能原因
- [uC/OS-II原理及应用]uC/OS-II的中断和时钟