Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4f2c830

Browse files
Create Convert Sorted Array to Binary Search Tree
1 parent 8806412 commit 4f2c830

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
想法:用 Divide and Conquer 的技巧,把目前考慮的矩陣中間作為 root,其餘左右再分別構建子樹即可
2+
終止條件是如果現在已經沒有矩陣需考慮就回傳 nullptr
3+
4+
Time Complexity : O(n) for constructing n nodes
5+
Space Complexity : O(n) for the binary tree
6+
7+
/**
8+
* Definition for a binary tree node.
9+
* struct TreeNode {
10+
* int val;
11+
* TreeNode *left;
12+
* TreeNode *right;
13+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
14+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
15+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
16+
* };
17+
*/
18+
class Solution {
19+
private:
20+
TreeNode* constructTree(vector<int>& nums , int startindex , int size) {
21+
if (size == 0)
22+
return nullptr ;
23+
24+
int middle = startindex + size / 2 ;
25+
return new TreeNode(nums[middle] ,
26+
constructTree(nums , startindex , middle - startindex) ,
27+
constructTree(nums , middle + 1 , startindex + size - middle - 1)) ;
28+
}
29+
public:
30+
TreeNode* sortedArrayToBST(vector<int>& nums) {
31+
return constructTree(nums , 0 , nums.size()) ;
32+
}
33+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /