table of Contents
Source of topic: https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
Title description
Enter the results of pre-order traversal and mid-order traversal of a binary tree, and please rebuild the binary tree. Assume that the input result of pre-order traversal and middle-order traversal does not contain repeated numbers.
General idea
- Recursion and divide and conquer, decompose the global problem into local sub-problems, and merge the overall problem by solving the sub-problems
- When the recursion termination condition is recursive, one of the two parameters is empty
Recursion
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty() || inorder.empty())
return nullptr;
TreeNode* head = new TreeNode(preorder[0]);
int root = 0;
for(int i = 0 ; i < preorder.size(); ++i){
// 维护 preorder[0] 为 容器首部元素
if(inorder[i] == preorder[0]){
root = i;
break;
}
}
vector<int> newLeftPre, newLeftIn;
vector<int> newRightPre, newRightIn;
for(int i = 0 ; i < root ; ++i){
// 写为preorder[i],会导致第一次分治添加preorder[0]
// 则在下次递归时preorder[0]还是根节点
newLeftPre.push_back(preorder[i + 1]);
newLeftIn.push_back(inorder[i]);
}
for(int i = root + 1; i < preorder.size(); ++i){
newRightPre.push_back(preorder[i]);
newRightIn.push_back(inorder[i]);
}
head->left = buildTree(newLeftPre, newLeftIn);
head->right = buildTree(newRightPre, newRightIn);
return head;
}
};
Complexity analysis
- Time complexity: O(n). n is the length of the array
- Space complexity: O(n). The space used by the recursive stack is O(n)