[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/
思路:递归实现,以中间节点作为根节点。
View Code
第二遍记录:注意二分的时候边界问题 和 mid 溢出问题。
第三遍记录:
类似二分查找,注意边界检查。
参考:
http://blog.csdn.net/xshengh/article/details/12705769
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
相关文章推荐
- [LeetCode] Convert Sorted Array to Binary Search Tree, Solution
- leetcode 11: Convert Sorted Array to Binary Search Tree
- leetcode - Convert Sorted Array to Binary Search Tree
- [leetcode刷题系列]Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree
- Leetcode: Convert Sorted Array to Binary Search Tree
- leetcode -- Convert Sorted Array to Binary Search Tree
- [leetcode] Convert Sorted Array to Binary Search Tree
- [Leetcode 32] 108 Convert Sorted Array to Binary Search Tree
- LeetCode_Convert Sorted Array to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree
- [Leetcode] Convert Sorted Array to Binary Search Tree
- Leetcode: Convert Sorted Array to Binary Search Tree
- leetcode 11: Convert Sorted Array to Binary Search Tree
- leetcode: Convert Sorted Array to Binary Search Tree
- arrayfunction[LeetCode]Convert Sorted Array to Binary Search Tree
- [LeetCode]Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree