[Leetcode] Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

跟上一题一样,只是数据结构换成了链表,这里求链表的中位数还是乖乖用len先计算长度吧,用slow、fast指针还得先标记尾指针,反而更麻烦。

 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     void buildTree(TreeNode *&root, ListNode *head, int len) {

21         if (len <= 0) return;

22         ListNode *mid = head;

23         for (int i = 0; i < len / 2; ++i) {

24             mid = mid->next;

25         }

26         root = new TreeNode(mid->val);

27         ListNode *head2 = mid->next;

28         mid = NULL;

29         buildTree(root->left, head, len / 2);

30         buildTree(root->right, head2, (len - 1) / 2);

31     }

32     

33     TreeNode *sortedListToBST(ListNode *head) {

34         int len = 0;

35         for (ListNode *p = head; p!= NULL; p = p->next) {

36             ++len;

37         }

38         TreeNode *root = NULL;

39         buildTree(root, head, len);

40         return root;

41     }

42 };

 

你可能感兴趣的:(Binary search)