//Definition of TreeNode: class TreeNode { public: int val; TreeNode *left, *right; TreeNode() { this->val = NULL; } TreeNode(int val) { this->val = val; this->left = this->right = NULL; } }; class Solution { /** *@param preorder : A list of integers that preorder traversal of a tree *@param inorder : A list of integers that inorder traversal of a tree *@return : Root of a tree */ public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { // recursive return TreeNode *root;
// 迭代到没有再返回 if (preorder.size() == 0 || inorder.size() == 0) { root = NULL; return NULL; } // write your code here int rootValue = preorder[0]; root = new TreeNode(rootValue); int index; for (int i = 0; i < inorder.size(); i++) { if (inorder[i] == rootValue) { index = i; break; } } //黑科技构造vector,迭代器可以这么用 vector<int> lchild_preorder(preorder.begin() + 1, preorder.begin() + 1 + index); vector<int> lchild_inorder(inorder.begin(), inorder.begin() + index); int lchild_len = lchild_preorder.size(); vector<int> rchild_preorder(preorder.begin() + index + 1, preorder.end()); vector<int> rchild_inorder(inorder.begin() + index + 1, inorder.end()); int rchild_len = rchild_preorder.size(); if (root!=NULL) { //root->val = rootValue; root->left = buildTree(lchild_preorder, lchild_inorder); root->right = buildTree(rchild_preorder, rchild_inorder); } return root; } };
http://www.lintcode.com/zh-cn/problem/construct-binary-tree-from-preorder-and-inorder-traversal/
accepted