LeetCode "Construct Binary Tree from Preorder and Inorder Traversal"
2014-07-23 03:29
375 查看
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
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode-Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode刷题系列]Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode]Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 109: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal, Solution
- [Leetcode 78] 105 Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- leetcode -- Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode-Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal (中序和后序建树,在题目给的函数中完成)【leetcode】
- leetcode之Construct Binary Tree from Preorder and Inorder Traversal