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

spo*_*234 2 tree binary-tree r binary-search-tree

我正在练习递归并尝试从链表实现 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)
Run Code Online (Sandbox Code Playgroud)

这是我尝试递归解决这个问题,但它不起作用:

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)
Run Code Online (Sandbox Code Playgroud)

我的错误在哪里?

小智 5

例如,您需要使用允许构建树的结构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))
}
Run Code Online (Sandbox Code Playgroud)