您的位置:首页 > 其它

[leetcode] Convert Sorted Array to Binary Search Tree

2014-07-02 23:40 441 查看
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

思路:递归实现,以中间节点作为根节点。

public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return toBST(num,0,num.length);
}
private TreeNode toBST(int[] num, int from, int to){
if(to-from<=0)
return null;
int mid=(from+to)/2;
TreeNode root = new TreeNode(num[mid]);
root.left=toBST(num,from,mid);
root.right=toBST(num,mid+1,to);

return root;
}
}


View Code

第二遍记录:注意二分的时候边界问题 和 mid 溢出问题。

public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return toBST(num,0,num.length-1);
}

private TreeNode toBST(int[]num, int from, int to){
if(from>to){
return null;
}
int mid = (to-from)/2+from;
TreeNode root = new TreeNode(num[mid]);
root.left=toBST(num,from,mid-1);
root.right=toBST(num,mid+1,to);
return root;
}

}


第三遍记录:

类似二分查找,注意边界检查。

参考:

http://blog.csdn.net/xshengh/article/details/12705769
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: