[LeetCode]108 Covert Sorted Aray to Binary Search Tree
1071 ワード
https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
http://fisherlei.blogspot.com/2013/03/leetcode-convert-sorted-array-to-binary.html
http://fisherlei.blogspot.com/2013/03/leetcode-convert-sorted-array-to-binary.html
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// O(log n)
public TreeNode sortedArrayToBST(int[] num) {
// height balanced BST.
// , list ( )
//
// root
TreeNode root = build(num, 0, num.length - 1);
return root;
}
private TreeNode build(int[] num, int low, int high)
{
if (low > high)
return null;
if (low == high)
return new TreeNode(num[low]);
int mid = (low + high) / 2;
TreeNode node = new TreeNode(num[mid]);
node.left = build(num, low, mid - 1);
node.right = build(num, mid + 1, high);
return node;
}
}