Solution: 1/**2* Definition for binary tree3* public class TreeNode {4* int val;5* TreeNode left;6* TreeNode right;7* TreeNode(int x) { val = x; }8* }9*/10publicclassSolution {11publicTreeNode sortedArrayToBST(
TreeNode* sortedArrayToBST(vector<int>& nums,intstart,intend){if(start > end)returnnullptr;intmid = (start + end) /2; TreeNode*root =newTreeNode(nums[mid]); root->left = sortedArrayToBST(nums, start, mid -1); root->right = sortedArrayToBST(nums, mid +1, end);returnroot; } ...
public TreeNode sortedArrayToBST(int[] nums) { return sortedArrayToBST(nums, 0, nums.length); } private TreeNode sortedArrayToBST(int[] nums, int start, int end) { if (start == end) { return null; } int mid = (start + end) >>> 1; TreeNode root = new TreeNode(nums[mid]...
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofeverynode never differ by more than 1. Example: Given the sorted array:...
def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ def build_bst(arr, i, j): if i > j: return None mid = (i+j)>>1 node = TreeNode(arr[mid]) node.left = build_bst(arr, i, mid-1) ...
Given an integer arraynumswhere the elements are sorted inascending order, convertit to aheight-balancedbinary search tree. Example 1: Input:nums = [-10,-3,0,5,9]Output:[0,-3,9,-10,null,5]Explanation:[0,-10,5,null,-3,null,9] is also accepted: ...
大概思路是要做一个root, 一个left subtree, right subtree. 但是我一开始只有一个function,我发现要recursion的时候, array不是很好取middle point。 因为比如最开始Array是[1,3,4,5,6,7,8,9]. 第一次mid point拿到root以后,要把middle point的左右分成两个子array 继续recursion, 类似[1,3,4,5], [7...
public: TreeNode *sortedArrayToBST(vector<int> &num) { return create(num,0,num.size()-1); } TreeNode* create(vector<int>num,int L,int R) { if(L>R)return NULL; int mid=(R+L+1)/2; //BST树总是从左到右排满的,如果不优先选右边的这个,{1,3}结果为{1,#,3},而实际结果应为...
push(temp->right); } } cout<<"\nend of level: "<<count<<endl; } int main(){ int n,no; cout<<"enter no of elements\n"; cin>>n; vector<int> v; cout<<"enter the sorted array\n"; while(n--){ cin>>no; v.push_back(no); } TreeNode* root=sortedArrayToBST(v); cout...
(low<=high) { int mid = (low+high)/2; TreeNode root = new TreeNode(num[mid]); root.left = creatBST(low,mid-1,num); root.right = creatBST(mid+1,high,num); return root; } else return null; } public TreeNode sortedArrayToBST(int[] num) { return creatBST(0,num.length-1,...