做题链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
这道题较为简单,采用递归方式就可以轻松解决,但是由于对C++编程不太熟悉,也费了点功夫。
此处采用了首尾序号标记法,没有重复构建数组,以免占用过多内存。
元素查找处的代码可做进一步优化,以降低时间复杂度。
/**
* 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>& preorder, vector<int>& inorder, int root_index=0, int start=0, int end=-1) {
if(-1 == end) end = inorder.size();
if(start >= end) return NULL;
int data = preorder[root_index];
TreeNode *root = new TreeNode(data);
if(1 == (end - start)) return root;
int index = start;
while(index < end){
if(inorder[index] == data) break;
index++;
}
root->left = buildTree(preorder, inorder, root_index + 1, start, index);
root->right = buildTree(preorder, inorder, root_index + 1 + (index - start), index + 1, end);
return root;
}
};