Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
is sorted in a strictly increasing order.public TreeNode sortedArrayToBST(int[] num) {
if (num.length == 0) {
return null;
}
TreeNode head = helper(num, 0, num.length - 1);
return head;
}
public TreeNode helper(int[] num, int low, int high) {
if (low > high) { // Done
return null;
}
int mid = (low + high) / 2;
TreeNode node = new TreeNode(num[mid]);
node.left = helper(num, low, mid - 1);
node.right = helper(num, mid + 1, high);
return node;
}
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param num, a list of integers
# @return a tree node
# 12:37
def sortedArrayToBST(self, num):
if not num:
return None
mid = len(num) // 2
root = TreeNode(num[mid])
root.left = self.sortedArrayToBST(num[:mid])
root.right = self.sortedArrayToBST(num[mid+1:])
return root
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.size() == 0) return NULL;
if(num.size() == 1)
{
return new TreeNode(num[0]);
}
int middle = num.size()/2;
TreeNode* root = new TreeNode(num[middle]);
vector<int> leftInts(num.begin(), num.begin()+middle);
vector<int> rightInts(num.begin()+middle+1, num.end());
root->left = sortedArrayToBST(leftInts);
root->right = sortedArrayToBST(rightInts);
return root;
}
};
In our experience, we suggest you solve this Convert Sorted Array to Binary Search Tree LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Convert Sorted Array to Binary Search Tree LeetCode Solution
I hope this Convert Sorted Array to Binary Search Tree LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>