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
解题:题目要求根据一个有序的数组创建一个二叉排序树,并且返回这个排序树。要求高度最小,那么必定是平衡二叉树,每次取有序序列最中间的那个数作为结点即可。递归方法,代码如下:
1 /**
2 * Definition of TreeNode:
3 * public class TreeNode {
4 * public int val;
5 * public TreeNode left, right;
6 * public TreeNode(int val) {
7 * this.val = val;
8 * this.left = this.right = null;
9 * }
10 * }
11 */
12
13
14 public class Solution {
15 /*
16 * @param A: an integer array
17 * @return: A tree node
18 */
19 public TreeNode sortedArrayToBST(int[] A) {
20 // write your code here
21 return create(A, 0, A.length - 1);
22 }
23 private TreeNode create(int[]A, int first, int last){
24 if(first >last)
25 return null;
26 int mid = (first + last) / 2;
27 TreeNode node = new TreeNode( A[mid] );
28 node.left = create(A, first, mid-1);
29 node.right = create(A, mid+1, last);
30 return node;
31 }
32 }