递归(分治):
c++
public/private的函数都调用的成员变量,需要放在public函数外,写在public一个函数里,private函数不能调用
class Solution {
public:
unordered_map<int, int> index;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
if(n==0){
return nullptr;
}
for (int i = 0; i < n; i++) {
index[inorder[i]] = i;
}
return rebuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
}
private:
TreeNode* rebuildTree(const vector<int>& preorder, const vector<int>& inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right){
if (preorder_left > preorder_right) {
return nullptr;
}
int preorder_root = preorder_left;
int inorder_root = index[preorder[preorder_root]];
TreeNode* root = new TreeNode(preorder[preorder_root]);
int size_left_subtree = inorder_root - inorder_left;
root->left = rebuildTree(preorder, inorder, preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root - 1);
root->right = rebuildTree(preorder, inorder, preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right);
return root;
}
};
public的多个函数都调用的成员变量,需要放在public函数外,写在public一个函数里,public其他函数不能调用
class Solution {
public:
unordered_map<int, int> index;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
if(n==0){
return nullptr;
}
for (int i = 0; i < n; i++) {
index[inorder[i]] = i;
}
return rebuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
}
TreeNode* rebuildTree(const vector<int>& preorder, const vector<int>& inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right){
if (preorder_left > preorder_right) {
return nullptr;
}
int preorder_root = preorder_left;
int inorder_root = index[preorder[preorder_root]];
TreeNode* root = new TreeNode(preorder[preorder_root]);
int size_left_subtree = inorder_root - inorder_left;
root->left = rebuildTree(preorder, inorder, preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root - 1);
root->right = rebuildTree(preorder, inorder, preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right);
return root;
}
};
python
index = {element: i for i, element in enumerate(inorder)}
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def reBuildTree(preorder_left, preorder_right, inorder_left, inorder_right):
if preorder_left > preorder_right:
return None
preorder_root = preorder_left
inorder_root = index[preorder[preorder_root]]
root = TreeNode(preorder[preorder_root])
size_left_subtree = inorder_root - inorder_left
root.left = reBuildTree(preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root - 1)
root.right = reBuildTree(preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right)
return root
n = len(preorder)
if n==0:
return None
index = {}
for i in range(n):
index[inorder[i]] = i;
return reBuildTree(0, n - 1, 0, n - 1);
|