首页 > 代码库 > Leetcode: Convert Sorted Array to Binary Search Tree

Leetcode: Convert Sorted Array to Binary Search Tree

基本上一次过,要注意边界条件的问题:如果在recursion里有两个参数int begin, end, 递归写作recursion(num, mid+1, end), 因为+号的原因,递归中是会出现begin > end 的情况的,所以考虑初始条件的时候应该要考虑充分。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode sortedArrayToBST(int[] num) {
12         if (num.length == 0) return null;
13         return construct(num, 0, num.length - 1);
14     }
15     
16     public TreeNode construct(int[] num, int begin, int end) {
17         if (begin > end) return null; 
18         if (begin == end) return new TreeNode(num[begin]);
19         int mid = (begin + end) / 2;
20         TreeNode root = new TreeNode(num[mid]);
21         root.left = construct(num, begin, mid-1);
22         root.right = construct(num, mid+1, end);
23         return root;
24     }
25 }