将排序的双链表转换为BST



如何将排序的双链表转换为平衡二叉搜索树

我正在考虑这样做,就像将数组转换为平衡的BST一样。找到中心,然后递归地转换DLL的左部分和右部分。例如

1 2 3 4 5 => 1 2 (3) 4 5=>

     3
   /   
  2     4
 /       
1         5

这导致递归式T(n) = 2T(n/2) + O(n)。O(n)表示寻找中心。因此,时间复杂度为0 (nlogn)。我想知道是否有一种算法可以在O(n)内完成此操作。

有O(n)个解。请注意,在BST上的有序遍历是按照期望的顺序遍历元素,因此只需在大小为n的初始空树上执行有序遍历,并用列表中的元素填充它。[在遍历中插入到树中的第i个元素,是列表中的第i个元素]。
在答案的最后,我添加了如何在O(n)中创建一个空平衡树。

:[假设树列表| | = = | |)

global current <- null
fillTree(tree,list):
  current <- list.head
  fillTree(tree)
fillTree(tree):
  if tree == null:
     return
  fillTree(tree.left)
  //in-order traversal: we set the value after setting left, and before calling right
  tree.val <- current.val
  current <- current.next
  fillTree(tree.right)

复杂度一般为O(n),因为树的每个顶点正好有一次迭代,每次迭代为O(1)。

编辑:


你可以创建一个空的平衡树,通过简单地构建一个空的完整树(*),它是平衡的,构建它是O(n)。

(*)完全二叉树是指除了最后一层以外的每一层都被完全填充的二叉树。

晚了将近4年。这就是我的函数解。以下是我在haskell中的代码,复杂度也是O(n):

import Data.List hiding (insert)
data Color = R | B deriving Show
data RBTree a = RBEmpty | RBTree { color :: Color
                                 , ltree :: RBTree a
                                 , nod   :: a
                                 , rtree :: RBTree a } deriving Show
fromOrdList ::  Ord e => [e] -> RBTree e
fromOrdList [] = empty
fromOrdList lst = 
    let (res, _) = _fol lst $ length lst
    in res
    where _fol :: (Ord e, Integral a) => [e] -> a -> (RBTree e, Maybe (e, [e]))
          _fol l 0            = (empty, uncons l)
          _fol (h:l) 1        = (RBTree B empty h empty, uncons l)
          _fol (h1:h2:l) 2    = (RBTree B (RBTree R empty h1 empty) h2 empty, uncons l)
          _fol (h1:h2:h3:l) 3 = (RBTree B (RBTree R empty h1 empty) h2 (RBTree R empty h3 empty), uncons l)
          _fol l n            =
            let mid                  = n `div` 2
                (ltr, Just (rt, tl)) = _fol l mid
                (rtr, mayremain)     = _fol tl (n - 1 - mid)
in (RBTree B ltr rt rtr, mayremain)

这实际上是我个人实践的一部分:https://github.com/HuStmpHrrr/PFDSPractise/blob/master/src/Tree/RBTree.hs#L97

看看我的递归插入实现(c#)。有T(n) = 2*T(n/2) + O(1)O(1)是求中心的(l+r)/2。所以复杂度是O(n)

public class Tree<T>
  {
    public class TreeNode<T>
    {
      public TreeNode<T> Right { get; set; }
      public TreeNode<T> Left { get; set; }
      public T Data { get; set; }
    }
    public Tree()
    {
      Root = new TreeNode<T>();
    }  
    public TreeNode<T> Root { get; set; }
    private void InsertSortedListRec(IList<T> items, TreeNode<T> curNode, int l, int r)
    {
      var mid = (l + r)/2;
      curNode.Data = items[mid];
      if (mid - 1 >= l)
      {
        curNode.Left = new TreeNode<T>();
        InsertSortedListRec(items, curNode.Left, l, mid - 1);
      }
      if (mid + 1 <= r)
      {
        curNode.Right = new TreeNode<T>();
        InsertSortedListRec(items, curNode.Right, mid + 1, r);
      }
  }
    public void InsertSortedList(IList<T> items)
    {
      InsertSortedListRec(items, Root, 0, items.Count - 1);
    }
  }

我假设我们有一个索引数组(我们可以将链表转换为数组O(n))

最新更新