[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
2013-01-24 15:36
483 查看
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *build(vector<int> &inorder, vector<int> &postorder, int s, int t, int p, int q) { if (s > t || p > q) return NULL; int pivot = postorder[q]; int v; for (v = s; v <= t; v++) { if (inorder[v] == pivot) break; } TreeNode *parent = new TreeNode(pivot); parent->left = build(inorder, postorder, s, v - 1, p, p + (v - s) - 1); parent->right = build(inorder, postorder, v + 1, t, p + (v - s), q - 1); return parent; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function return build(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); } };
Small Case: 12ms
Large Case: 112ms
Time: O(nlgn)
Space: O(1)
相关文章推荐
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- leetcode-106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]题解(python):106-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 Preorder and Inorder Traversal, Construct Binary Tree from Inorder and Postorder Traversal
- leetcode -- Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode 106] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode Construct Binary Tree from Inorder and Postorder Traversal 难度系数3 3.38
- LeetCode_106 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 [106]