//根据先序序列pre[pre_low..pre_low+len-1]和中序序列in[in_low..in_low+len-1]建树t
时间: 2024-01-07 18:02:30 浏览: 29
TreeNode* buildTree(vector<int>& pre, int pre_low, int pre_high, vector<int>& in, int in_low, int in_high) {
if (pre_low > pre_high || in_low > in_high) {
return nullptr;
}
int root_val = pre[pre_low];
int root_index_in = in_low;
while (root_index_in <= in_high && in[root_index_in] != root_val) {
root_index_in++;
}
int left_len = root_index_in - in_low;
TreeNode* root = new TreeNode(root_val);
root->left = buildTree(pre, pre_low+1, pre_low+left_len, in, in_low, root_index_in-1);
root->right = buildTree(pre, pre_low+left_len+1, pre_high, in, root_index_in+1, in_high);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.empty() || inorder.empty() || preorder.size() != inorder.size()) {
return nullptr;
}
return buildTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)