Convert Sorted Array to Binary Search Tree | Leetcode 108 | Live coding session

preview_player
Показать описание
Here is the solution to "Convert Sorted Array to Binary Search Tree" leetcode question. Hope you have a great time going through it.

Solution

1) 0:00 Explaining the problem out loud
2) 1:10 Algorithm walkthrough
3) 2:30 Solution for Convert Sorted array to BST
4) 4:00 Time Complexity

PS : Please increase the speed to 1.25X
Рекомендации по теме
Комментарии
Автор

Easy true, I think you have already done a similar question in the past.

neetugoyal
Автор

what is the time complexity of this approach ?

TreeNode root=null;


//Time complexity of this approach is o(nlogn);
//Space complexity is o(1);
public TreeNode sortedArrayToBST(int[] nums) {
constructBST(nums, 0, nums.length - 1);
return root;
}

private void constructBST(int[] nums, int low, int high) {

if (low > high)
return ;

int mid = low + (high - low) / 2;

if (root == null)
root = new TreeNode(nums[mid]);
else {
TreeNode node = new TreeNode(nums[mid]);
TreeNode cur=root;
TreeNode tail=null;
while (cur!=null){
if(node.val<cur.val) {
tail=cur;
cur = cur.left;
}
else {
tail=cur;
cur = cur.right;
}
}
if(node.val<tail.val)
tail.left=node;
else
tail.right=node;
}
constructBST(nums, low, mid - 1);
constructBST(nums, mid + 1, high);
}


Thanks in advance.

praveenj