File tree Expand file tree Collapse file tree 3 files changed +60
-0
lines changed
1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008 Expand file tree Collapse file tree 3 files changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ cmake_minimum_required (VERSION 3.13 )
2
+ project (D )
3
+
4
+ set (CMAKE_CXX_STANDARD 14 )
5
+
6
+ add_executable (D main.cpp )
Original file line number Diff line number Diff line change
1
+ // / Source : https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
2
+ // / Author : liuyubobobo
3
+ // / Time : 2019-03-09
4
+
5
+ #include < iostream>
6
+ #include < vector>
7
+
8
+ using namespace std ;
9
+
10
+
11
+ // / Definition for a binary tree node.
12
+ struct TreeNode {
13
+ int val;
14
+ TreeNode *left;
15
+ TreeNode *right;
16
+ TreeNode (int x) : val(x), left(NULL ), right(NULL ) {}
17
+ };
18
+
19
+
20
+ // / Recursive
21
+ // / Time Complexity: O(n^2)
22
+ // / Space Complexity: O(1)
23
+ class Solution {
24
+ public:
25
+ TreeNode* bstFromPreorder (vector<int >& preorder) {
26
+
27
+ int n = preorder.size ();
28
+ return dfs (preorder, 0 , n - 1 );
29
+ }
30
+
31
+ private:
32
+ TreeNode* dfs (const vector<int >& v, int l, int r){
33
+
34
+ if (l > r || l >= v.size () || r >= v.size ()) return NULL ;
35
+
36
+ TreeNode* root = new TreeNode (v[l]);
37
+
38
+ int i;
39
+ for (i = l + 1 ; i <= r; i ++)
40
+ if (v[i] > v[l]) break ;
41
+
42
+ root->left = dfs (v, l + 1 , i - 1 );
43
+ root->right = dfs (v, i, r);
44
+ return root;
45
+ }
46
+ };
47
+
48
+
49
+ int main () {
50
+
51
+ return 0 ;
52
+ }
Original file line number Diff line number Diff line change @@ -674,4 +674,6 @@ email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com)
674
674
| 1005 | [ Maximize Sum Of Array After K Negations] ( https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/ ) | [ 无] | [ C++] ( 1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005/ ) | | |
675
675
| 1006 | [ Clumsy Factorial] ( https://leetcode.com/problems/clumsy-factorial/ ) | [ 无] | [ C++] ( 1006-Clumsy-Factorial/cpp-1006/ ) | | |
676
676
| 1007 | [ Minimum Domino Rotations For Equal Row] ( https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ ) | [ 无] | [ C++] ( 1007-Minimum-Domino-Rotations-For-Equal-Row/cpp-1007/ ) | | |
677
+ | 1008 | [ Construct Binary Search Tree from Preorder Traversal] ( https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ ) | [ 无] | [ C
678
+ ++] ( 1008-Construct-Binary-Search-Tree-from-Preorder-Traversal/cpp-1008/ ) | | |
677
679
| | | | | | |
You can’t perform that action at this time.
0 commit comments