思路:
1.树中的第一个值为根(数组的第一个值),小于根的值存放在左子树中,大于根的值存放在右子树中;
2.利用递归对左右子树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
return fun(preorder,0,preorder.size()-1);
}
TreeNode* fun(vector<int>& preorder,int left,int right){
//如果左边大于右边,直接返回空
if(left>right) return nullptr;
//获取根节点的值
int root = preorder[left];
TreeNode *node = new TreeNode(root);
//找到大于根节点的值,并以此为左右子树的分界
int mid = left;
while(mid<right+1){
if(preorder[mid]>root) break;
mid++;
}
//递归生成左子树和右子树
node->left = fun(preorder,left+1,mid-1);
node->right = fun(preorder,mid,right);
return node;
}
};