Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

108. Convert Sorted Array to Binary Search Tree

Posted on 2020-03-26 | Edited on 2021-03-05

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/35220/My-Accepted-Java-Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums==null) return null;
return treeBuilder(0,nums.length-1,nums);
}
public TreeNode treeBuilder(int start,int end, int[] nums){
if(start>end) return null;
int mid=start+(end-start)/2;
TreeNode node=new TreeNode(nums[mid]);
node.left=treeBuilder(start,mid-1,nums);
node.right=treeBuilder(mid+1,end,nums);
return node;
}
}
<1…257258259…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%