1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 TreeNode *sortedArrayToBST(vector<int> &num) {
13 TreeNode* root = 0;
14 constructBST(num, 0, num.size()-1, root);
15 return root;
16 }
17
18 void constructBST(vector<int>& num, int ibegin, int iend, TreeNode*& root) { //root是引用
19 if(ibegin > iend) return;
20 int mid = ibegin + (iend-ibegin)/2; //取中间的元素
21 root = new TreeNode(num[mid]); //建立根节点
22 constructBST(num, ibegin, mid-1, root->left); //构建左子树
23 constructBST(num, mid+1, iend, root->right); //构建右子树
24 }
25 };
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 /**
10 * Definition for binary tree
11 * struct TreeNode {
12 * int val;
13 * TreeNode *left;
14 * TreeNode *right;
15 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
16 * };
17 */
18 class Solution {
19 public:
20 TreeNode *sortedListToBST(ListNode *head) {
21 TreeNode* root = 0;
22 constructBST(head, root);
23 return root;
24 }
25
26 void constructBST(ListNode* head, TreeNode*& root) {
27 if( !head ) return ; //如果链表为空,则说明子树为空
28 ListNode* pre = 0; //slow的前驱节点
29 ListNode* fast = head; //快指针,每次走两步
30 ListNode* slow = head; //慢指针,每次走一步
31 while( fast && fast->next ) {
32 fast = fast->next->next;
33 pre = slow;
34 slow = slow->next;
35 }
36 ListNode* lhead = 0; //新左链表
37 ListNode* rhead = slow->next; //新右链表
38 ListNode* midNode = slow; //中间节点
39 midNode->next = 0;
40 if( pre ) { //如果新左链表不为空的情况
41 lhead = head;
42 pre->next = 0;
43 }
44 root = new TreeNode(midNode->val); //利用中间元素构建根节点
45 delete midNode;
46 constructBST(lhead, root->left); //构建左子树
47 constructBST(rhead, root->right); //构建右子树
48 }
49 };