从R中的排序列表创建二叉搜索树

问题描述 投票:1回答:1

我正在练习递归并试图从链表中实现BST。我试图将解决方案从这里转换为R:Create Balanced Binary Search Tree from Sorted linked list

给定矢量vec我想找到BST,例如:

  0
  / \
 -3   9
 /   /
-10  5


vec <- c(-10,-3,0,5,9)

这是我尝试以递归方式解决此问题,但它不起作用:

tobt <- function(vec, start, end) {
  if (start > end) return(NA)
  mid <- start + (end - start) / 2
  left <- tobt(vec, start, mid-1)
  right <- tobt(vec, mid+1, end)
  return(c(left, right))
}

tobt(vec, 1, 5)

我的错误在哪里?

r tree binary-tree binary-search-tree
1个回答
3
投票

您需要使用允许构建树的结构,例如list。第二个问题是忽略用数字填充树节点的父节点。

您功能的可能变体:

tobt <- function(vec, start, end) {
  if (start > end) return(NULL)
  mid <- start + (end - start) %/% 2
  left <- tobt(vec, start, mid-1)
  parent <- vec[mid]
  right <- tobt(vec, mid+1, end)
  return(list(left=left, node = parent, right=right))
}
© www.soinside.com 2019 - 2024. All rights reserved.