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; } };
小心驶得万年船
LeetCode Construct Binary Tree from Preorder and Inorder Traversal,布布扣,bubuko.com
LeetCode Construct Binary Tree from Preorder and Inorder Traversal
原文地址:http://www.cnblogs.com/lailailai/p/3845071.html