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、设置两个指针one和two,一个走一步,一个走两步,当two指针走到链表的尾部时,one指针便走到了链表的中心节点位置

2、找到链表的中心节点后,剩下的步骤和http://www.cnblogs.com/laihaiteng/p/3795524.html这篇文章中的思路相同,不过边界条件(即递归的基本条件)要特别注意,可能每个人的做法不同会引起基本条件不同,我这里的是尾指针为NULL或者头指针是尾指针的下一个节点,则返回NULL

代码:

 1 #include <stddef.h>
 2 
 3 struct ListNode
 4 {
 5     int val;
 6     ListNode *next;
 7     ListNode(int x) : val(x), next(NULL) {}
 8 };
 9 
10 struct TreeNode
11 {
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 {
20 public:
21     TreeNode *sortedListToBST(ListNode *head)
22     {
23         if (!head)
24         {
25             return NULL;
26         }
27 
28         ListNode *tail = head;
29         while (tail->next)
30         {
31             tail = tail->next;
32         }
33 
34         TreeNode *root = build(head, tail);
35 
36         return root;
37     }
38 private:
39     TreeNode *build(ListNode *begin, ListNode *end)
40     {
41         ListNode *one = begin;
42         ListNode *two = begin;
43         ListNode *middle = NULL;
44         ListNode *middle_pre = NULL;
45         ListNode *middle_next = NULL;
46 
47         if (!begin || end->next == begin)
48         {
49             return NULL;
50         }
51 
52         while (two != end)
53         {
54             middle_pre = one;
55             one = one->next;
56             two = two->next;
57             if (two == end)
58             {
59                 break;
60             }
61             two = two->next;
62         }
63         middle = one;
64         middle_next = middle->next;
65 
66         TreeNode *root = new TreeNode(middle->val);
67         root->left = build(begin, middle_pre);
68         root->right = build(middle_next, end);
69 
70         return root;
71     }
72 };
View Code

 

网上看了一些文章,大致思路都是这样的,可能略微有一些小改动,就不贴出来了。

posted on 2014-06-21 18:26  laihaiteng  阅读(253)  评论(0编辑  收藏  举报

导航