reConstructBinaryTree Posted on 2019-02-28 | In Routine | 问题:输入某二叉树的前序遍历和中序遍历的结果,重建二叉树,假设前序遍历和中序遍历的结果中都不包含重复的数字 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#include <iostream>#include <vector>using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: TreeNode *build(vector<int> &pre, int p_l, int p_r, vector<int> &vin, int v_l, int v_r) { // 找到pre[p_l]在vim中的位置 TreeNode *cur = new TreeNode(pre[p_l]); if (p_l == p_r) { return cur; } int count = 0; for (int i = v_l; i <= v_r; i++) { if (vin[i] == pre[p_l]) { count = i - v_l; } } // if (count == 0) { cur->right = build(pre, p_l + 1, p_r, vin, v_l + 1, v_r); } else if (v_l + count == v_r) { cur->left = build(pre, p_l + 1, p_r, vin, v_l, v_r - 1); } else { cur->left = build(pre, p_l + 1, p_l + count, vin, v_l, v_l + count - 1); cur->right = build(pre, p_l + count + 1, p_r, vin, v_l + count + 1, v_r); } return cur; } TreeNode *reConstructBinaryTree(vector<int> pre, vector<int> vin) { TreeNode *root = build(pre, 0, pre.size() - 1, vin, 0, vin.size() - 1); return root; }};int main() { vector<int> pre = {1, 2, 4, 7, 3, 5, 6, 8}; vector<int> vin = {4, 7, 2, 1, 5, 3, 8, 6}; Solution solution; TreeNode *root = solution.reConstructBinaryTree(pre, vin); return 0;}