Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
一個小小的下標沒搞好,居然要浪費差不多一個小時,心痛啊。
中序遍歷序列和後序遍歷序列的偏移位置都需要仔細設計好。
class Solution { public: TreeNode *buildTree(vector&preorder, vector &inorder) { return conTree(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1); } TreeNode *conTree(vector &preo, vector &ino, int prel, int prer, int inl, int inr) { if (prel > prer) return NULL; TreeNode *t = new TreeNode(preo[prel]); auto it = find(ino.begin()+inl, ino.begin()+inr+1, preo[prel]); int offset = it-ino.begin()-inl; //注意:切記,下標如何定位要清楚,是offset還是絕對位置不能搞混了! t->left = conTree(preo, ino, prel+1, prel+offset, inl, inl+offset-1); t->right = conTree(preo, ino, prel+offset+1, prer, inl+offset+1, inr); return t; } };