您的位置:首页 > 其它

递归---Convert Sorted Array to Binary Search Tree With Minimal Height

2016-01-25 14:54 519 查看
Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.

Have you met this question in a real interview? Yes

Example

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

4

/ \

2 6

/ \ / \

1 3 5 7

Note

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

Tags Expand

/**
* 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
*/
private TreeNode buildTree(int[] num, int start, int end) {
if (start > end) {
return null;
}

TreeNode node = new TreeNode(num[(start + end) / 2]);
node.left = buildTree(num, start, (start + end) / 2 - 1);
node.right = buildTree(num, (start + end) / 2 + 1, end);
return node;
}

public TreeNode sortedArrayToBST(int[] A) {
// write your code here
if (A == null) {
return null;
}
return buildTree(A, 0, A.length - 1);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: