Convert Sorted Array to Binary Search Tree - Tree - Easy - LeetCode
💻 coding

Convert Sorted Array to Binary Search Tree - Tree - Easy - LeetCode

1 min read 181 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to convert a sorted array into a height-balanced binary search tree (BST).
  • 2A height-balanced BST ensures that the depth of subtrees of any node differs by no more than one.
  • 3The provided solution has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to convert a sorted array into a height-balanced binary search tree (BST)."

Convert Sorted Array to Binary Search Tree - Tree - Easy - LeetCode

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

0 / \ -3 9 / / -10 5

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * public int val;
 * public TreeNode left;
 * public TreeNode right;
 * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution {
 public TreeNode SortedArrayToBST(int[] nums) { 
 var tree = Helper(nums,0,nums.Length-1);
 return tree;
 }
 
 private TreeNode Helper(int[] nums, int start, int end){
 if(start>end){
 return null;
 }
 var tree = new TreeNode();
 int mid = (start+end)/2;
 tree.val = nums[mid];
 tree.left = Helper(nums,start,mid-1);
 tree.right = Helper(nums,mid+1,end);
 return tree;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 6 October 2020 · 1 min read · 181 words

Part of AskGif Blog · coding

You might also like