剑指Offer——重建二叉树
2017-06-29 19:59
495 查看
Question
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。Solution
首先先序遍历的第一个数字是根,然后从中序遍历中,通过根的值,可以将数组分为左子树(左边的)和右子树(右边的)。然后取出左子树的先序遍历和中序遍历部分就可以用于构建这颗子树,方法和刚才一样,可以看到这个是一个递归的过
程,右子树同理。
Code
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if (pre.size() == 0 || vin.size() == 0) return NULL; return ConstructBinaryTreeCore(pre, vin, 0, pre.size() - 1, 0, vin.size() - 1); } TreeNode* ConstructBinaryTreeCore(vector<int>& pre, vector<int>& vin, int pre_start, int pre_end, int vin_start, int vin_end) { int rootValue = pre[pre_start]; TreeNode* root = new TreeNode(rootValue); if (pre_start == pre_end) { if (vin_start == vin_end) return root; else { //throw exception("Invalid input"); } } int rootVin = vin_start; while (rootVin <= vin_end && vin[rootVin] != rootValue) rootVin++; if (vin_start == vin_end && vin[rootVin] != rootValue) { //throw exception("Invalid input"); } int leftLength = rootVin - vin_start; int leftPreEnd = pre_start + leftLength; if (leftLength > 0) { root->left = ConstructBinaryTreeCore(pre, vin, pre_start + 1, leftPreEnd, vin_start, rootVin - 1); } if (leftLength < pre_end - pre_start) { root->right = ConstructBinaryTreeCore(pre, vin, leftPreEnd + 1, pre_end, rootVin + 1, vin_end); } return root; } };
相关文章推荐
- 剑指offer面试题06 重建二叉树
- 剑指Offer:面试题6重建二叉树
- 剑指Offer [04] 重建二叉树
- 面试题06_重建二叉树——剑指offer系列
- 剑指offer(三十三)之重建二叉树
- 《剑指offer》面试题6 重建二叉树
- 《剑指offer》重建二叉树
- 《剑指Offer》面试题六之重建二叉树
- 《剑指offer》编程题java实现(二十六):重建二叉树(两种方法)
- 【剑指offer系列】 重建二叉树___6
- (剑指offer)重建二叉树
- 剑指offer题解C++【4】重建二叉树
- 《剑指offer》牛客网java题解-重建二叉树
- 《剑指offer》问题7 重建二叉树 Java实现
- 剑指Offer学习之面试题6 :重建二叉树
- 理解《剑指Offer》之面试题6 重建二叉树
- 剑指offer 二叉树重建
- 剑指offer 重建二叉树 旋转数组的最小数字 链表中倒数第k个结点 反转链表
- 剑指Offer编程练习004——重建二叉树
- 剑指OFFER----重建二叉树