108. Convert Sorted Array to Binary Search Tree
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class Solution { TreeNode* helper(vector<int>& A, int l, int r) { if(l > r) return nullptr; int m = l + (r - l) / 2; TreeNode* node = new TreeNode(A[m]); node->left = helper(A,l,m-1); node->right = helper(A,m+1,r); return node; } public: TreeNode* sortedArrayToBST(vector<int>& nums) { return helper(nums,0,nums.size()-1); } };
|