剑指offer-004
来源:互联网 发布:侧吸 顶吸 知乎 编辑:程序博客网 时间:2024/06/12 21:33
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
先序遍历:根左右
中序遍历:左根右
*/
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector pre,vector in) {
//结点个数为0, 或者前序结点个数与中序结点个数不同
if (pre.size() ==0 || in.size() == 0 || pre.size() != in.size()) return NULL;
//由前序得到根结点 int rootValue = pre[0]; TreeNode *root = new TreeNode(rootValue); if (pre.size() == 1){ if (pre[0] == in[0]) return root; else return NULL; } //遍历中序序列找到根结点 int rootIn = 0; while (rootIn < in.size() && in[rootIn] != rootValue){ ++rootIn; } //中序序列中没有根结点 if (rootIn == in.size() && in[rootIn] != rootValue) return NULL; //递归左子树 //计算左子树的前序 和 中序 序列 vector<int> leftPre; vector<int> leftIn; for (int i = 1; i <= rootIn; i++){ leftPre.push_back(pre[i]); leftIn.push_back(in[i-1]); } if (leftPre.size() > 0){ root -> left = reConstructBinaryTree(leftPre, leftIn); } //递归右子树 vector<int> rightPre; vector<int> rightIn; for (int i = rootIn + 1; i < pre.size(); ++i){ rightPre.push_back(pre[i]); rightIn.push_back(in[i]); } if (rightPre.size() > 0){ root -> right = reConstructBinaryTree(rightPre, rightIn); } return root;}
};
0 0
- 剑指offer-004
- 剑指offer-004
- 剑指Offer--004-替换空格
- 剑指OFFER
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 《剑指offer》
- 苍狼敏捷软件开发团队建设指南-1-团队模型
- 负载均衡,会话保持,session同步
- thinkphp登录代码
- 融云获取Token
- 余弦计算相似度度量
- 剑指offer-004
- Two Sum
- WinCE6.0开发环境搭建
- php的json和数组转换
- Android--从零单排系列(6)--相对应对话框popupwindow的优势和使用
- 数据库的字段不够用的时候,可以将数据存为json格式
- 面试题2
- UML建模详解(7)—Rose时序图绘制总结
- IOS Dev Intro - NSThread of Thread Series