Convert Sorted Array to Binary Search Tree Solutions in C++
Number 108
Difficulty Easy
Acceptance 58.1%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/// Author : Hao Chen// Date : 2014-06-23/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:TreeNode *sortedArrayToBST(vector<int> &num) {if(num.size()==0){return NULL;}if(num.size()==1){return new TreeNode(num[0]);}int mid = num.size()/2;TreeNode *node = new TreeNode(num[mid]);vector<int>::const_iterator first;vector<int>::const_iterator last;first = num.begin();last = num.begin()+mid;vector<int> v(first, last);node->left = sortedArrayToBST(v);if (mid==num.size()-1){node->right = NULL;}else{first = num.begin()+mid+1;last = num.end();vector<int> v(first, last);node->right = sortedArrayToBST(v);}return node;}};
C++ solution by pezy/LeetCode
/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/#include <vector>#include <cstddef>using std::vector;struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:TreeNode *sortedArrayToBST(vector<int> &num) {return sortedArrayToBST(num.begin(), num.end());}TreeNode *sortedArrayToBST(vector<int>::iterator beg, vector<int>::iterator end){if (beg == end) return NULL;auto mid = beg + (end - beg)/2;TreeNode *root = new TreeNode(*mid);root->left = sortedArrayToBST(beg, mid);root->right = sortedArrayToBST(std::next(mid), end);return root;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description//// Author : liuyubobobo/// Time : 2018-10-30#include <iostream>#include <vector>using namespace std;/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/// Recursion/// Time Complexity: O(n)/// Space Complexity: O(logn)class Solution {public:TreeNode* sortedArrayToBST(vector<int>& nums) {if(nums.size() == 0)return NULL;return buildTree(nums, 0, nums.size() - 1);}private:TreeNode* buildTree(const vector<int>& nums, int l, int r){if(l > r) return NULL;if(l == r) return new TreeNode(nums[l]);int mid = (l + r) / 2;TreeNode* root = new TreeNode(nums[mid]);root->left = buildTree(nums, l, mid - 1);root->right = buildTree(nums, mid + 1, r);return root;}};int main() {return 0;}