R: создание рекурсивного двоичного дерева в R - PullRequest
1 голос
/ 05 мая 2020

Мне интересно написать алгоритм рекурсивного двоичного дерева. Учитывая следующие данные, в которых я уже отсортировал ковариату x

mydata <- data.frame(x = c(10, 20, 25, 35), y = c(-10.5, 6.5, 7.5, -7.5))
> mydata
   x     y
1 10 -10.5
2 20   6.5
3 25   7.5
4 35  -7.5

, я разделю дерево так, чтобы левый узел всегда содержал первый экземпляр родительского узла, а правый узел содержал остальные экземпляры в родительском узле (странный способ разделения, но, пожалуйста, потерпите меня). По сути, я хочу, чтобы мое дерево выглядело так с максимальной высотой = 3.

          [-10.5, 6.5, 7.5, -7.5]
                /         \
           [-10.5]        [6.5, 7.5, -7.5]
                            /      \
                       [6.5]       [7.5, -7.5]

Я хочу, чтобы конечный результат моей функции возвращал список, содержащий все узлы:

> final_tree
[[1]]
[[1]][[1]]
   x     y
1 10 -10.5
2 20   6.5
3 25   7.5
4 35  -7.5


[[2]]
[[2]][[1]]
   x     y
1 10 -10.5


[[2]][[2]]
   x     y
1 20   6.5
2 25   7.5
3 35  -7.5


[[3]]
[[3]][[1]]
NULL

[[3]][[2]]
NULL

[[3]][[3]]
   x     y
1 20   6.5


[[3]][[4]]
   x     y
1 25   7.5
2 35  -7.5

Вот что у меня есть:

# Initialize empty tree
create_empty_tree <- function(max_height) sapply(1:max_height, function(k) replicate(2**(k-1),c()))

# Create empty tree with max_height = 3
tree_struc <- create_empty_tree(max_height = 3)

grow_tree <- function(node_parent, max_height, tree_struc, height){
  # Sort x
  sorted_x <- sort(node_parent$x)

  # Fix best split index at 1
  best_split_ind <- 1

  # Assign instances to left or right nodes
  group <- ifelse(node_parent$x <= node_parent$x[best_split_ind], "left", "right")
  node_left <- node_parent[which(group == "left"), ]
  node_right <- node_parent[which(group == "right"), ]

  # Recursive call on left and right nodes
  if(height < max_height){
  tree_struc[[height]] <- node_parent
  tree_struc[[height + 1]][[1]] <- grow_tree(node_parent = node_left, max_height = max_height, tree_struc = tree_struc, height = height + 1)
  tree_struc[[height + 1]][[2]] <- grow_tree(node_parent = node_right, max_height = max_height, tree_struc = tree_struc, height = height + 1)
  }

  return(tree_struc)
}

grow_tree(node_parent = mydata, max_height = 3, tree_struc = tree_struc, height = 1)

Полученное дерево неверно. Я думаю, это связано с тем, как я рекурсивно вызвал функцию на левом и правом дочерних узлах. Может ли кто-нибудь указать мне правильное направление?

1 Ответ

0 голосов
/ 05 мая 2020

Может быть, вы можете попробовать функцию grow_tree ниже

create_empty_tree <- function(max_height) sapply(1:max_height, function(k) replicate(2**(k-1),c()))

grow_tree <- function(node_parent,max_height = nrow(node_parent)) {
  tree_struc <- create_empty_tree(max_height)
  for (i in 1:length(tree_struc)) {
    tree_struc[[i]][[2**(i-1)]] <- `row.names<-`(tail(node_parent,nrow(node_parent)-i+1),NULL)
    if (i > 1) tree_struc[[i]][[2**(i-1)-1]] <- `row.names<-`(node_parent[i-1,],NULL)
  }
  tree_struc
}

Пример

> grow_tree(mydata,3)
[[1]]
[[1]][[1]]
   x     y
1 10 -10.5
2 20   6.5
3 25   7.5
4 35  -7.5


[[2]]
[[2]][[1]]
   x     y
1 10 -10.5

[[2]][[2]]
   x    y
1 20  6.5
2 25  7.5
3 35 -7.5


[[3]]
[[3]][[1]]
NULL

[[3]][[2]]
NULL

[[3]][[3]]
   x   y
1 20 6.5

[[3]][[4]]
   x    y
1 25  7.5
2 35 -7.5

и

> grow_tree(mydata)
[[1]]
[[1]][[1]]
   x     y
1 10 -10.5
2 20   6.5
3 25   7.5
4 35  -7.5


[[2]]
[[2]][[1]]
   x     y
1 10 -10.5

[[2]][[2]]
   x    y
1 20  6.5
2 25  7.5
3 35 -7.5


[[3]]
[[3]][[1]]
NULL

[[3]][[2]]
NULL

[[3]][[3]]
   x   y
1 20 6.5

[[3]][[4]]
   x    y
1 25  7.5
2 35 -7.5


[[4]]
[[4]][[1]]
NULL

[[4]][[2]]
NULL

[[4]][[3]]
NULL

[[4]][[4]]
NULL

[[4]][[5]]
NULL

[[4]][[6]]
NULL

[[4]][[7]]
   x   y
1 25 7.5

[[4]][[8]]
   x    y
1 35 -7.5
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...