重建二叉树 -- C++迭代器解法
重建二叉树
http://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6
class Solution { public: typedef vector<int>::iterator vit; TreeNode* reConstructBinaryTree(const vit &preBeg,const vit &preEnd, const vit &vinBeg,const vit &vinEnd) { if (preBeg == preEnd) return nullptr; TreeNode *root = new TreeNode(*preBeg); const vit &it = find(vinBeg, vinEnd, *preBeg); auto size = it - vinBeg; // cout << root->val << size << endl; root->left = reConstructBinaryTree(preBeg + 1, preBeg + 1 + size, vinBeg, it); root->right = reConstructBinaryTree(preBeg + 1 + size, preEnd, it + 1, vinEnd); return root; } TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { return reConstructBinaryTree(pre.begin(), pre.end(), vin.begin(), vin.end()); } };