[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.

这题的关键是能找出当前链表的中间节点,然后再递归左右的子链表,开始的时候程序先计算链表总厂,然后传入两个前后索引指针,最后每次递归找出中间节点即可。

 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     int calLen(ListNode *node)

21     {

22         int len = 0;

23         while(node)

24         {

25             len++;

26             node = node->next;

27         }

28         return len;

29     }

30     

31     TreeNode *createTree(ListNode *node, int left, int right)

32     {

33         if (left > right)

34             return NULL;

35             

36         int mid = (left + right) / 2;

37         

38         ListNode *p = node;

39         

40         for(int i = left; i < mid; i++)

41             p = p->next;

42             

43         TreeNode *leftNode = createTree(node, left, mid - 1);

44         TreeNode *rightNode = createTree(p->next, mid + 1, right);

45         

46         TreeNode *tNode = new TreeNode(p->val);

47         

48         tNode->left = leftNode;

49         tNode->right = rightNode;

50         

51         return tNode;        

52     }

53     

54     TreeNode *sortedListToBST(ListNode *head) {

55         // Start typing your C/C++ solution below

56         // DO NOT write int main() function

57         int len = calLen(head);

58         return createTree(head, 0, len - 1);

59     }

60 };

 

 

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