leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
2017-06-03 11:46
417 查看
1.题目
Given inorder and postorder traversal of a tree, construct the binary tree.Note:
You may assume that duplicates do not exist in the tree
2.思路
递归.每次从后续遍历最后得到root,然后根据前序分割left tree和right tree,之后递归.3.代码
/*** Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
// inorder: left-root-right
//postorder: left-right-root
public:
TreeNode* create(vector<int> &inorder, vector<int> &postorder, int is, int ie, int ps, int pe){
if(ps > pe){
return nullptr;
}
TreeNode* node = new TreeNode(postorder[pe]);
//找到inorder中root位置
int pos;
for(int i = is; i <= ie; i++){
if(inorder[i] == node->val){
pos = i;
break;
}
}
node->left = create(inorder, postorder, is, pos - 1, ps, ps + pos - is - 1);
node->right = create(inorder, postorder, pos + 1, ie, pe - ie + pos, pe - 1);
return node;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return create(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
}
};
相关文章推荐
- [Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode --- 106. Construct Binary Tree from Inorder and Postorder Traversal
- Java for LeetCode 106 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 106] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 105/106 Construct Binary Tree from Preorder/Postorder and Inorder Traversal
- LeetCode 106:Construct Binary Tree from Postorder and Inorder Traversal
- [Leetcode 106, Medium] 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: 106_Construct Binary Tree from Inorder and Postorder Traversal | 根据中序和后序遍历构建二叉树 | Medium
- [Leetcode 79] 106 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_106_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 [106]
- [LeetCode]106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal