Convert Sorted List to Binary Search Tree

Question

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

题解 - 折半取中

Convert Sorted Array to Binary Search Tree | Data Structure and Algorithm 的升级版,不过这里把「有序数组」换成了「有序链表」。我们可以参考上题的题解思路,思考如何才能在链表中找到「中间节点」。对于本题的单向链表来说,要想知道中间位置的节点,则必须需要知道链表的长度,因此我们就自然联想到了可以通过遍历链表来求得其长度。求得长度我们就知道了链表中间位置节点的索引了,进而根据头节点和当前节点则可将链表分为左右两半形成递归模型。到这里还只能算是解决了问题的一半,这道题另一比较麻烦的地方在于边界条件的取舍,很难第一次就 AC, 下面结合代码做进一步的分析。

C++

  1. /**
  2. * Definition of ListNode
  3. * class ListNode {
  4. * public:
  5. * int val;
  6. * ListNode *next;
  7. * ListNode(int val) {
  8. * this->val = val;
  9. * this->next = NULL;
  10. * }
  11. * }
  12. * Definition of TreeNode:
  13. * class TreeNode {
  14. * public:
  15. * int val;
  16. * TreeNode *left, *right;
  17. * TreeNode(int val) {
  18. * this->val = val;
  19. * this->left = this->right = NULL;
  20. * }
  21. * }
  22. */
  23. class Solution {
  24. public:
  25. /**
  26. * @param head: The first node of linked list.
  27. * @return: a tree node
  28. */
  29. TreeNode *sortedListToBST(ListNode *head) {
  30. if (NULL == head) {
  31. return NULL;
  32. }
  33. // get the size of List
  34. ListNode *node = head;
  35. int len = 0;
  36. while (NULL != node) {
  37. node = node->next;
  38. ++len;
  39. }
  40. return buildBSTHelper(head, len);
  41. }
  42. private:
  43. TreeNode *buildBSTHelper(ListNode *head, int length) {
  44. if (NULL == head || length <= 0) {
  45. return NULL;
  46. }
  47. // get the middle ListNode as root TreeNode
  48. ListNode *lnode = head;
  49. int count = 0;
  50. while (count < length / 2) {
  51. lnode = lnode->next;
  52. ++count;
  53. }
  54. TreeNode *root = new TreeNode(lnode->val);
  55. root->left = buildBSTHelper(head, length / 2);
  56. root->right = buildBSTHelper(lnode->next, length - 1 - length / 2);
  57. return root;
  58. }
  59. };

源码分析

  1. 异常处理。
  2. 获取链表长度。
  3. buildBSTHelper输入参数为表头节点地址以及相应的链表长度,递归获取根节点、左节点和右节点。

其中buildBSTHelper的边界处理很有技巧,首先是递推的终止条件,头节点为NULL时显然应该返回NULL. 但length的终止条件又如何确定?拿不定主意时就用几个简单例子来试试,比如1, 1->2, 1->2->3.

先来分析下给buildBSTHelper传入的length的含义——从表头节点head开始往后递推长度为length的链表。故length为0时表示不访问链表中的任一节点,也就是说应该返回NULL.

再来分析链表的中间位置如何确定,我们引入计数器count来表示目前需要遍历count个链表节点数目才能得到中间位置的节点。看看四种不同链表长度下的表现。

  1. 链表长度为1时,中间位置即为自身,计数器的值为0.
  2. 链表长度为2时,中间位置可选第一个节点,也可选第二个节点,相应的计数器值为0或1.
  3. 链表长度为3时,中间位置为第二个节点,相应的计数器应为1,表示从表头节点往后递推一个节点。
  4. 链表长度为4时,… 计数器的值为1或者2.

从以上四种情况我们可以推断出count的值可取为length / 2或者length / 2 + 1, 简单起见我们先取length / 2试试,对应的边界条件即为count < length / 2, count初始值为0. 经过count次迭代后,目前lnode即为所需的链表中间节点,取出其值初始化为TreeNode的根节点。

确定根节点后还需要做的事情就是左子树和右子树中链表头和链表长度的取舍。首先来看看左子树根节点的确定,count的含义为到达中间节点前遍历过的链表节点数目,那么从另一方面来说它就是前半部分链表的长度!故将此长度length / 2作为得到左子树根节点所需的链表长度参数。除掉链表前半部分节点和中间位置节点这两部分外,剩下的链表长度即为length - 1 - length / 2.

Warning length - 1 - length / 2 != length / 2 - 1

有没有觉得可以进一步化简为length / 2 - 1? 我首先也是这么做的,后来发现一直遇到TERMSIG= 11错误信息,这种错误一般是指针乱指或者指针未初始化就去访问。但自己仔细检查后发现并没有这种错误,于是乎在本地做单元测试,发现原来是死循环造成了栈空间溢出(猜的)!也就是说边界条件有问题!可自己的分析明明是没啥问题的啊…

在这种情况下我默默地打开了九章的参考代码,发现他们竟然没有用length / 2 - 1,而是length - 1 - length / 2. 立马意识到这两者可能并不相等。用错误数据试了下,长度为1或者3时两者即不相等。知道对于整型数来说,1 / 2为0,但是却没能活学活用,血泪的教训。:-( 一个美好的下午就没了。

在测试出错的时候,还是要相信测试数据的力量,而不是凭自己以前认为对的方式去解决问题。

复杂度分析

首先遍历链表得到链表长度,复杂度为 O(n). 递归遍历链表时,每个链表节点被访问一次,故时间复杂度为 O(n), 两者加起来总的时间复杂度仍为 O(n).

进一步简化代码

  1. class Solution {
  2. public:
  3. TreeNode *sortedListToBST(ListNode *head) {
  4. int length = 0;
  5. ListNode *curr = head;
  6. while (curr != NULL) {
  7. curr = curr->next;
  8. ++length;
  9. }
  10. return helper(head, length);
  11. }
  12. private:
  13. TreeNode *helper(ListNode *&pos, int length) {
  14. if (length <= 0) {
  15. return NULL;
  16. }
  17. TreeNode *left = helper(pos, length / 2);
  18. TreeNode *root = new TreeNode(pos->val); // the sequence cannot be changed!
  19. // this is important difference of the solution above
  20. pos = pos->next;
  21. root->left = left;
  22. root->right = helper(pos, length - length / 2 - 1);
  23. return root;
  24. }
  25. };

源码分析

  1. 可以进一步简化 helper 函数代码,注意参数的接口设计。
  2. 即是把传入的链表指针向前递进 n 步,并返回经过的链表节点转化成的二分查找树的根节点。
  3. 注意注释中的那两句实现,new rootnew left 不可调换顺序。这才是精简的要点。但是这种方法不如上面的分治法容易理解。

O(nlogn) 的实现,避免 length 边界

  1. /**
  2. * Definition for ListNode.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int val) {
  7. * this.val = val;
  8. * this.next = null;
  9. * }
  10. * }
  11. * Definition of TreeNode:
  12. * public class TreeNode {
  13. * public int val;
  14. * public TreeNode left, right;
  15. * public TreeNode(int val) {
  16. * this.val = val;
  17. * this.left = this.right = null;
  18. * }
  19. * }
  20. */
  21. public class Solution {
  22. /**
  23. * @param head: The first node of linked list.
  24. * @return: a tree node
  25. */
  26. public TreeNode sortedListToBST(ListNode head) {
  27. if (head == null) {
  28. return null;
  29. }
  30. return helper(head);
  31. }
  32. private TreeNode helper(ListNode head) {
  33. if (head == null) {
  34. return null;
  35. }
  36. if (head.next == null) {
  37. return new TreeNode(head.val);
  38. }
  39. ListNode pre = null;
  40. ListNode slow = head, fast = head;
  41. while (fast != null && fast.next != null) {
  42. pre = slow;
  43. slow = slow.next;
  44. fast = fast.next.next;
  45. }
  46. pre.next = null;
  47. TreeNode root = new TreeNode(slow.val);
  48. TreeNode L = helper(head);
  49. TreeNode R = helper(slow.next);
  50. root.left = L;
  51. root.right = R;
  52. return root;
  53. }
  54. }

源码分析

  1. 如果想避免上述 length 边界搞错的问题,可以使用分治法遍历树求中点的方法。
  2. 但这种时间复杂度是 $$O(nlogn)$$,性能上还是比 $$O(n)$$ 差一点。

Reference