[剑指offer] 重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { int len = pre.size(); if (len <= 0) return NULL; if (len == 1) return new TreeNode(pre[0]); TreeNode* re = new TreeNode(pre[0]); int lenLeft = 0; for (; lenLeft < vin.size(); lenLeft++) { if (vin[lenLeft] == pre[0]) break; } int lenRight = len - lenLeft - 1; vector<int> preLeft(pre.begin() + 1, pre.begin() + lenLeft + 1); vector<int> vinLeft(vin.begin(), vin.begin() + lenLeft); vector<int> preRight(pre.begin() + lenLeft + 1, pre.end()); vector<int> vinRight(vin.begin() + lenLeft + 1, vin.end()); re->left = reConstructBinaryTree(preLeft, vinLeft); re->right = reConstructBinaryTree(preRight, vinRight); return re; } };