将有序单链表转换为平衡的二叉搜索树

题目:

给定一个升序排列的有序单链表,将其转换为一棵平衡的二叉搜索树。

分析:

单链表的结点结构如下。

struct node {
     int data; 
     struct node *next;
};

由于单链表升序排列,可以参照前面的文章
将有序数组转换为平衡二叉搜索树, 先求的链表中的结点的值保存在数组中,然后采用相同的方法实现,时间复杂度为O(N)。当然也可以不额外采用数组保存结点值,只是在每次递归的时候需要找出链表的中间元素,由于每次查找中间元素需要O(N/2)的时间,一共需要O(lgN)查找,所以总的时间为O(NlgN)。

更好的解法

我们可以采用自底向上的方法,在这里我们不再需要每次查找中间元素。下面代码依旧需要链表长度作为参数,计算链表长度时间复杂度为O(N),而转换算法时间复杂度也为O(N),所以总的时间复杂度为O(N)。

BinaryTree* sortedListToBST(struct node*& list, int start, int end) {
  if (start > end) return NULL;
  // same as (start+end)/2, avoids overflow
  int mid = start + (end - start) / 2;
  BinaryTree *leftChild = sortedListToBST(list, start, mid-1);
  BinaryTree *parent = new BinaryTree(list->data);
  parent->left = leftChild;
  list = list->next;
  parent->right = sortedListToBST(list, mid+1, end);
  return parent;
}
 
BinaryTree* sortedListToBST(struct node *head, int n) {
  return sortedListToBST(head, 0, n-1);
}

代码中需要注意的是每次调用sortedListToBST函数时,list位置都会变化,调用完函数后list总是指向mid+1的位置(如果满足返回条件,则list位置不变)。 例如如果链表只有2个节点3->5->NULL,则初始start=0,end=1。则mid=0,继而递归调用sortedListToBST(list, start,mid-1),此时直接返回NULL。即左孩子为NULL, 根结点为3,而后链表list指向5,再调用sortedListToBST(list, mid+1, end),而这次调用返回结点5,将其赋给根结点3的右孩子。这次调用的mid=1,调用完成后list已经指向链表末尾。

英文地址
Convert Sorted List to Balanced Binary Search Tree

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/sgbfblog/article/details/7867429
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞