您的位置:首页 > 其它

Convert Sorted Array to Binary Search Tree - Leetcode

2015-02-26 12:31 627 查看
/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return sortedArrayToBSTHelper(0,num.length-1,num);
}
private TreeNode sortedArrayToBSTHelper(int start, int end, int[] num){
int len = end-start+1;
if(len <= 0)
return null;

int mid = start+len/2;
TreeNode root= new TreeNode(num[mid]);
root.left = sortedArrayToBSTHelper(start, mid-1, num);
root.right = sortedArrayToBSTHelper(mid+1, end, num);

return root;
}
}


分析,用笔画一下,就发现,你要构造一个树先确定他的root, 即中值。然后找root的左/右子树,也就是继续在左/右边区域找中值,直到所有值都安排到相应的位置了。

Given an array where elements are sorted in ascending order, convert it to a
height balanced BST.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: