1.Array
class Solution {
public:
TreeNode *Tree(int left, int right, vector<int> &num){
TreeNode *root = NULL;
if (left <= right){
int cen = (left + right) / 2;
root = new TreeNode(num[cen]);
root->left = Tree(left, cen - 1, num);
root->right = Tree(cen + 1, right, num);
}
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
TreeNode *T = NULL;
int N = num.size();
T = Tree(0, N - 1, num);
return T;
}
};class Solution {
public:
ListNode *findMid(ListNode *head){ //这里假设链表中仅仅有两个数字。则mid返回的是head->next.
if (head == NULL || head -> next == NULL)
return head;
ListNode *fast, *slow, *pre;
fast = slow = head;
pre = NULL;
while (fast && fast->next){
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = NULL;
return slow;
}
TreeNode *buildTree(ListNode *head){
TreeNode *root = NULL;
ListNode *mid = NULL;
if (head){
mid = findMid(head);
root = new TreeNode(mid->val);
if (head != mid){
root->left = buildTree(head);
root->right = buildTree(mid->next);
}
}
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
TreeNode *T;
T = buildTree(head);
return T;
}
};LeetCode :: Convert Sorted Array (link list) to Binary Search Tree [tree]
原文:http://www.cnblogs.com/mengfanrong/p/5097087.html