[leetcode]Construct Binary Tree from Preorder and Inorder Traversal
Posted on 2014-01-14 17:20 1957 阅读(2632) 评论(0) 编辑 收藏 举报从前序中序遍历来重构二叉树
经典题,从期末考试到考研什么的应该都有
前序遍历第一个肯定是root
在inorder里面去找root
左边的是leftsubtree , 右边的是rightsubtree
然后preorder除去order,后面lifetsubtree.size 个是左边的, rightsubtree.size个是右边的
递归构造tree就好了
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: template<typename Iter> TreeNode* make(Iter pFirst , Iter pLast , Iter iFirst , Iter iLast) { if(pFirst == pLast) return nullptr; if(iFirst == iLast) return nullptr; int val = *pFirst; auto iRoot = find(iFirst , iLast , val); TreeNode* root = new TreeNode(*iRoot); int leftSize = iRoot - iFirst; root -> left = make(pFirst+1 , pFirst+leftSize+1 , iFirst , iRoot); root -> right = make(pFirst+leftSize+1 , pLast , iRoot + 1 , iLast); return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { int size = inorder.size(); if(size == 0) return nullptr; return make(preorder.begin() , preorder.end() , inorder.begin() , inorder.end()); } };
by 1957