首页 > 代码库 > LeetCode Construct Binary Tree from Preorder and Inorder Traversal

LeetCode Construct Binary Tree from Preorder and Inorder Traversal

class Solution {public:    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {        int plen = preorder.size();        int ilen = inorder.size();        if (plen == 0 || ilen == 0) return NULL;        return dfs(preorder, inorder, 0, plen, 0, ilen);    }    TreeNode* dfs(vector<int> &preorder, vector<int> &inorder, int ps, int pe, int is, int ie) {        if (ps >= pe || is >= ie) return NULL;        int rval = preorder[ps];        int iroot= is;        while (iroot != ie && inorder[iroot] != rval) iroot++;        int pe_offset = (iroot - is) + ps + 1;        TreeNode* nroot = new TreeNode(rval);        nroot->left = dfs(preorder, inorder, ps + 1, pe_offset, is, iroot);        nroot->right= dfs(preorder, inorder, pe_offset, pe, iroot + 1, ie);        return nroot;    }};

小心驶得万年船