根据BST的前序遍历重建BST
1. 平均O(NlogN) 最坏O(N^2)
class Solution { public: TreeNode* dfs(int l, int r, vector<int>& p) { if (l > r) return nullptr; TreeNode* node = new TreeNode(p[l]); int i; for (i = l + 1; i <= r; ++i) { if (p[i] > p[l]) break; } node->left = dfs(l + 1, i - 1, p); node->right = dfs(i, r, p); return node; } TreeNode* bstFromPreorder(vector<int>& preorder) { return dfs(0, preorder.size() - 1, preorder); } };
2. O(N)
class Solution { public: int i = 0; TreeNode* bstFromPreorder(vector<int>& A, int bound = INT_MAX) { if (i == A.size() || A[i] > bound) return nullptr; TreeNode* root = new TreeNode(A[i++]); root->left = bstFromPreorder(A, root->val); root->right = bstFromPreorder(A, bound); return root; } };