[LeetCode]106. Construct Binary Tree from Inorder and Postorder Traversal
2017-08-18 22:44
375 查看
106. Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/** * 和之前使用中序和前序遍历重建的题一样,可以直接使用索引,避免反复创建vector,这里就省略不实现了... */ /** * 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 { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if(inorder.empty() || postorder.empty()) return NULL; TreeNode* root = new TreeNode(*(postorder.end()-1)); int i = 0; for(; i < inorder.size(); ++i){ if(inorder[i] == root->val) break; } if(i > 0){ vector<int> in_left = vector<int>(inorder.begin(), inorder.begin()+i); vector<int> post_left = vector<int>(postorder.begin(), postorder.begin()+i); root->left = buildTree(in_left, post_left); } if(i < inorder.size()-1){ vector<int> in_right = vector<int>(inorder.begin()+i+1, inorder.end()); vector<int> post_right = vector<int>(postorder.begin()+i, postorder.end()-1); root->right = buildTree(in_right, post_right); } return root; } };
相关文章推荐
- [leetcode 106] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106:Construct Binary Tree from Postorder and Inorder Traversal
- LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
- 【LeetCode】105 & 106 Construct Binary Tree from (Preorder and Inorder) || (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) (cpp)
- [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] 106. Construct Binary Tree from Inorder and Postorder Traversal
- [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
- C#解leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal