177. Convert Sorted Array to Binary Search Tree With Minimal Height【LintCode by java】

时间:2024-01-11 21:50:08

Description

Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.

There may exist multiple valid solutions, return any of them.

Example

Given [1,2,3,4,5,6,7], return

     4
/ \
2 6
/ \ / \
1 3 5 7

解题:题目要求根据一个有序的数组创建一个二叉排序树,并且返回这个排序树。要求高度最小,那么必定是平衡二叉树,每次取有序序列最中间的那个数作为结点即可。递归方法,代码如下:

 /**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/ public class Solution {
/*
* @param A: an integer array
* @return: A tree node
*/
public TreeNode sortedArrayToBST(int[] A) {
// write your code here
return create(A, 0, A.length - 1);
}
private TreeNode create(int[]A, int first, int last){
if(first >last)
return null;
int mid = (first + last) / 2;
TreeNode node = new TreeNode( A[mid] );
node.left = create(A, first, mid-1);
node.right = create(A, mid+1, last);
return node;
}
}