[LeetCode]Convert Sorted List to Binary Search Tree

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.

 

和上一题Convert Sorted Array to Binary Search Tree一样的道理,唯一的区别就是链表,不能直接取任意值。

注意取链表某个值的方法,就可以写出来。方法在纸上自己画下图就明白了。

 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 a binary tree node.
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 lengthOfList(ListNode* head)
21     {
22         int len = 0;
23         while(head)
24         {
25             len++;
26             head = head->next;
27         }
28         return len;
29     }
30     TreeNode* createTree(ListNode* head,int left,int right)
31     {
32         if(left>right) return NULL;
33         ListNode* p = head;
34         int mid = (left+right)/2;
35         for(int i=left;i<mid;i++) p=p->next;
36         TreeNode* leftTree = createTree(head,left,mid-1);
37         TreeNode* rightTree = createTree(p->next,mid+1,right);
38         TreeNode * root = new TreeNode(p->val);
39         root->left = leftTree;
40         root->right = rightTree;
41         return root;
42     }
43     TreeNode* sortedListToBST(ListNode* head) {
44         int n = lengthOfList(head);
45         createTree(head,0,n-1);
46     }
47 };

 

posted @ 2015-09-07 16:56  Sean_le  阅读(116)  评论(0编辑  收藏  举报