C++ 没记错的话这类树的大部分都是递归
/**
* 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* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
int vinlen=vin.size();
if(vinlen==0) return NULL;
vector<int> left_pre,right_pre,left_vin,right_vin;
TreeNode* head=new TreeNode(pre[0]);
int root=0;
for(int i=0;i<vinlen;i++)
if(vin[i]==pre[0]){
root=i;
break;
}
for(int i=0;i<root;i++){
left_vin.push_back(vin[i]);
left_pre.push_back(pre[i+1]);
}
for(int i=root+1;i<vinlen;i++){
right_vin.push_back(vin[i]);
right_pre.push_back(pre[i]);
}
head->left=reConstructBinaryTree(left_pre, left_vin);
head->right=reConstructBinaryTree(right_pre, right_vin);
return head;
}
};
Python(评论里的)
class Solution:
def reConstructBinaryTree(self, pre, tin):
if not pre or not tin:
return None
root = TreeNode(pre.pop(0))
index = tin.index(root.val)
root.left = self.reConstructBinaryTree(pre, tin[:index])
root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
return root