TreeNode *buildBST(vector<int> &num, int l, int h){ if(l==h){ return NULL; } TreeNode * root = new TreeNode(num[(l+h)/2]); root->left = buildBST(num,l,(l+h)/2); root->right = buildBST(num,(l+h)/2+1,h); return root; }
TreeNode* buildBST(ListNode *head, int listLen) { if (head == NULL || listLen == 0) { return NULL; } int nodeCount = 0; ListNode *node = head; while (node->next != NULL && nodeCount != listLen / 2) { nodeCount++; node = node->next; } TreeNode *root = new TreeNode(node->val); root->left = buildBST(head, nodeCount); root->right = buildBST(node->next, listLen - 1 - nodeCount); return root; }
TreeNode* buildBST(vector<int>& nums, int begin, int end){ if(begin >= end) return NULL; int mid = (begin + end)/2; TreeNode* root = new TreeNode(nums[mid]); TreeNode* left = buildBST(nums, begin, mid); TreeNode* right = buildBST(nums, mid+1, end); root->left = left; root->right = right; return root; }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* buildBST(struct ListNode* head, struct ListNode* end) { struct TreeNode* bst = (struct TreeNode*) malloc(sizeof(struct TreeNode)); struct ListNode* p = head, *q = head; if(head == end) return NULL; while(p!=end && p->next!=end){ p = p->next->next; q = q->next; } bst->val = q->val; bst->left = buildBST(head, q);//end will not be considered bst->right = buildBST(q->next, end); return bst; }
TreeNode* buildBST(ListNode* head) { if(head == NULL) return NULL; ListNode* pre = head; ListNode* slow = head; ListNode* fast = head; while(fast->next && fast->next->next) { pre = slow; slow = slow->next; fast = fast->next->next; } TreeNode* tree = new TreeNode(slow->val); //cout << slow->val << endl; if(pre != slow) pre->next = NULL; if(pre != slow) tree->left = buildBST(head); tree->right = buildBST(slow->next); return tree; }
TreeNode* sortedListToBST(ListNode *head) { if (head == NULL) { return NULL; } int listLen = 1; ListNode *node = head; while (node->next != NULL) { listLen++; node = node->next; } return buildBST(head, listLen); }
TreeNode* sortedListToBST(ListNode* head) { return buildBST(head); }
TreeNode *sortedArrayToBST(vector<int> &num) { return buildBST(num, 0, num.size()); }
TreeNode* sortedArrayToBST(vector<int>& nums) { int size = nums.size(); return buildBST(nums, 0, size); }
struct TreeNode* sortedListToBST(struct ListNode* head) { if(head == NULL)return NULL; return buildBST(head, NULL); }