Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:19
Show Gist options
  • Save HDegano/6b4279cfa95e208e29ac to your computer and use it in GitHub Desktop.
Save HDegano/6b4279cfa95e208e29ac to your computer and use it in GitHub Desktop.
Sorted Array to Balanced BST
/**
* Definition for binary tree
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode SortedArrayToBST(int[] num) {
return _sortedArrayToBST(num, 0, num.Length - 1);
}
private TreeNode _sortedArrayToBST(int[] num, int lo, int hi){
if(lo > hi) return null;
var mid = lo + (hi - lo)/2;
var root = new TreeNode(num[mid]);
root.left = _sortedArrayToBST(num, lo, mid-1);
root.right = _sortedArrayToBST(num, mid+1, hi);
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment