108.Convert Sorted Array to Binary Search Tree

题目链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/

题目大意:将一个升序数组转换成平衡二叉排序树。

法一(借鉴):一看到平衡二叉,就懵了,以为是用平衡转换来做,直接看了题解,发现并不是,用二分就可以做,毕竟还要满足排序树的特点,代码如下(耗时1ms):

 1     public TreeNode sortedArrayToBST(int[] nums) {
 2         return dfs(nums, 0, nums.length - 1);
 3     }
 4     
 5     public static TreeNode dfs(int[] nums, int left, int right) {
 6         if(left > right) {
 7             return null;
 8         }
 9         int mid = (left + right) / 2;
10         TreeNode root = new TreeNode(nums[mid]);
11         root.left = dfs(nums, left, mid - 1);
12         root.right = dfs(nums, mid + 1, right);
13         return root;
14     }
View Code

法二(借鉴):非递归解,虽然觉得有点多此一举,https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/

posted on 2017-11-01 08:51  二十年后20  阅读(150)  评论(0编辑  收藏  举报

导航