Last active
August 29, 2015 14:19
-
-
Save HDegano/6b4279cfa95e208e29ac to your computer and use it in GitHub Desktop.
Sorted Array to Balanced BST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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