Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/6322126 to your computer and use it in GitHub Desktop.
Save charlespunk/6322126 to your computer and use it in GitHub Desktop.
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
return build(num, 0, num.length - 1);
}
public TreeNode build(int[] num, int begin, int end){
if(begin > end) return null;
int mid = (begin + end) / 2;
TreeNode node = new TreeNode(num[mid]);
node.left = build(num, begin, mid - 1);
node.right = build(num, mid + 1, end);
return node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment