1 //[8,5,1,7,10,12] 2 class Solution 3 { 4 public: 5 TreeNode* solve(vector<int>& preorder,int l,int r) 6 { 7 if(l>r) 8 return NULL; 9 TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode)); 10 root -> val = preorder[l]; 11 if(l==r) 12 { 13 root -> left = root -> right = NULL; 14 return root; 15 } 16 int nr = -1; 17 for(int i = l+1;i <= r;i ++) 18 { 19 if(nr==-1 && preorder[i]>root->val) 20 nr = i; 21 } 22 if(nr==-1) 23 { 24 root->right = NULL; 25 root->left = solve(preorder,l+1,r); 26 return root; 27 } 28 root -> left = solve(preorder,l+1,nr-1); 29 root -> right = solve(preorder,nr,r); 30 return root; 31 } 32 TreeNode* bstFromPreorder(vector<int>& preorder) 33 { 34 return solve(preorder,0,preorder.size()-1); 35 } 36 };
这题应该叫先序遍历构建二叉搜索树。第一个肯定是根节点,往后找第一个比根节点大的数,那个就是右子树的根节点。根节点下一个就是左子树根节点。左子树根节点到右子树根节点之间就是左子树,右子树根节点到最后就是右子树。