Skip to content

Commit

Permalink
Create convertSortedArrayToBinarySearchTree.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
anishmo99 committed Oct 5, 2020
1 parent 756425f commit 9909cfe
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions DFS/convertSortedArrayToBinarySearchTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* 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) {}
* };
*/

// BINARY SEARCH

class Solution
{
public:
TreeNode *func(vector<int> &nums, int low, int high)
{
while (low <= high)
{
int mid = low + (high - low) / 2;

TreeNode *root = new TreeNode(nums[mid], func(nums, low, mid - 1), func(nums, mid + 1, high));

// TreeNode *root = new TreeNode(nums[mid]);
// root->left = func(nums, low, mid - 1);
// root->right = func(nums, mid + 1, high);

return root;
}
return nullptr;
}

TreeNode *sortedArrayToBST(vector<int> &nums)
{
return func(nums, 0, nums.size() - 1);
}
};

// FASTEST SOLUTION

class Solution
{
public:
TreeNode *sortedArrayToBST(vector<int> &nums)
{
if (nums.size() < 1)
return NULL;
int mid = (nums.size() / 2);
TreeNode *root = new TreeNode(nums[mid]);
vector<int> left(nums.begin(), nums.begin() + mid);
vector<int> right(nums.begin() + mid + 1, nums.end());
root->left = sortedArrayToBST(left);
root->right = sortedArrayToBST(right);
return root;
}
};

0 comments on commit 9909cfe

Please sign in to comment.