LeetCode "Construct Binary Tree from Inorder and Postorder Traversal"
2014-07-23 04:13
344 查看
Another textbook problem. We take back of postorder array as the current root, and then we can split the inorder array: 1st half for current right child, and 2nd for current left.
class Solution { public: TreeNode *_buildTree(int in[], int i0, int i1, int insize, int post[], int &inx_p) { if(inx_p < 0 || i0 > i1) return NULL; TreeNode *pRoot = new TreeNode(post[inx_p]); int iRoot = std::find(in, in + insize, post[inx_p--]) - in; TreeNode *pRight = _buildTree(in, iRoot + 1, i1, insize, post, inx_p); pRoot->right = pRight; TreeNode *pLeft= _buildTree(in, i0, iRoot-1, insize, post, inx_p); pRoot->left = pLeft; return pRoot; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { int *in = new int[inorder.size()]; std::copy(inorder.begin(), inorder.end(), in); int *post = new int[postorder.size()]; std::copy(postorder.begin(), postorder.end(), post); int inx = postorder.size() - 1; return _buildTree(in, 0, inorder.size()-1, inorder.size(), post, inx); } };
相关文章推荐
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- leetcode - Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode - Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode-Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- [面试真题] LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode刷题系列]Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode -- Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode::Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode-Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal