Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
这道题目A的过程很是艰辛,历经数次超时,终于找到原因。先瞅瞅我这超时的代码吧。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
int length = nums.length;
if (nums == null) //或者length == 0
return null;
return BuildBST(nums, 0, length-1);
}
public TreeNode BuildBST(int[] nums, int start, int end) {
if (start > end)
return null;
int mid = (start+end)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = BuildBST(nums, 0, mid-1); //错误的地方,应修改为root.left = BuildBST(nums, start, mid-1);
root.right = BuildBST(nums, mid+1, end);
return root;
}
}
原理依旧很简单,DFS,递归,只要找清楚mid,start和end,神马都好说。可是,我的问题依旧是Time Limit Exceeded。
Where is the problem? What the hell should I solve it!
仔细看代码,BuildBST方法出问题了,就在root.left那一行,参数传递错误,本应该传递start我却传递的是0.
修改之,root.left = BuildBST(nums, start, mid-1); 再次提交,Accepted.
再说说之前编码遇到的几个小问题,
1.判断nums为空,与判断nums.length为0是一个意思;
2.创建树,需要new一个TreeNode不够熟练;
3.定义方法的时候,一定注意参数的类型,像我刚开始就忘了定义start和end的类型了
4.最后返回的是root,就是我们的TreeNode.
没有评论:
发表评论