【ATT】Convert Sorted List to Binary Search Tree
bottom up.
TreeNode *sortedListToBST(ListNode *head) { // Note: The Solution object is instantiated only once and is reused by each test case. //1. getLength if(!head) return NULL; int len = 0; ListNode* cur = head; while(cur) { len++; cur = cur->next; } return build(head,0,len-1); } TreeNode* build(ListNode*& head,int start,int end) { if(start>end) return NULL; int mid = start + (end-start)/2; TreeNode* leftchild = build(head,start,mid-1); TreeNode* parent = new TreeNode(head->val); head = head->next; parent->left = leftchild; parent->right = build(head,mid+1,end); return parent; }