A collegiate textbook problem. Nothing special, but just take care of your memory use.
class Solution { public: TreeNode *_buildTree(int pre[], int &inx_p, int np, int in[], int i0, int i1) { if(inx_p == np || i0 == i1) return NULL; TreeNode *pRoot = new TreeNode(pre[inx_p]); int inx = std::find(in + i0, in + i1, pre[inx_p++]) - in; TreeNode *pLeft = _buildTree(pre, inx_p, np, in, i0, inx); TreeNode *pRight = _buildTree(pre, inx_p, np, in, inx + 1, i1); pRoot->left = pLeft; pRoot->right = pRight; return pRoot; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { int *pre = new int[preorder.size()]; std::copy(preorder.begin(), preorder.end(), pre); int *in = new int[inorder.size()]; std::copy(inorder.begin(), inorder.end(), in); int inx = 0; return _buildTree(pre, inx, preorder.size(), in, 0, inorder.size()); } };
LeetCode "Construct Binary Tree from Preorder and Inorder Traversal",布布扣,bubuko.com
LeetCode "Construct Binary Tree from Preorder and Inorder Traversal"
原文地址:http://www.cnblogs.com/tonix/p/3862041.html