[leetcode] Convert Sorted Array to Binary Search Tree
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; } }
第二遍记录:注意二分的时候边界问题 和 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; } }
第三遍记录:
类似二分查找,注意边界检查。
参考: