【问题标题】:R - Error while counting nodes in a binary tree: (list) object cannot be coerced to type 'logical'R - 计算二叉树中的节点时出错:(列表)对象不能被强制输入“逻辑”
【发布时间】:2018-02-09 18:04:31
【问题描述】:

我有一棵二叉树,结构如下:

> tree
$is_leaf
[1] FALSE
$prediction
[1] ""
$splitting_feature
[1] "term= 36 months"
$left
$left$splitting_feature
[1] ""
$left$left
[1] ""
$left$right
[1] ""
$left$is_leaf
[1] TRUE
$left$prediction
[1] -1
$right
$right$splitting_feature
[1] ""
$right$left
[1] ""
$right$right
[1] ""
$right$is_leaf
[1] TRUE
$right$prediction
[1] 1

我编写了以下递归函数来计算二叉搜索树中的节点数。

count_nodes<-function(tree){

        if(tree['is_leaf']==TRUE)
        {return(1)} else{

                return(1+count_nodes(tree['left']) + count_nodes(tree['right']))    
                }

}

当我把这个函数称为

> count_nodes(tree)

我收到以下错误

Error in count_nodes(tree["left"]) : 
  (list) object cannot be coerced to type 'logical'

dput(tree)如下:

> dput(tree)
structure(list(is_leaf = FALSE, left = structure(list(is_leaf = TRUE, 
    left = "", right = ""), .Names = c("is_leaf", "left", "right"
)), right = structure(list(is_leaf = TRUE, left = "", right = ""), .Names = c("is_leaf", 
"left", "right"))), .Names = c("is_leaf", "left", "right"))
> 

请帮忙解决这个问题。提前致谢。

【问题讨论】:

  • 请在您的tree 对象上dput 并添加相关问题。它将帮助人们回答。
  • @MKR 感谢您的建议。我添加了 dput(tree) 的输出

标签: r count tree binary-tree nodes


【解决方案1】:

当您使用单括号对列表进行子集时,您将获得一个子列表。要提取列表的元素,请使用双括号。

这是使用单括号时出现的错误:

tree <- list(
  is_leaf = F,
  left = list(is_leaf = T, left = "", right = ""),
  right = list(is_leaf = T, left = "", right = ""))

count_nodes <- function(tree){
  if(tree['is_leaf'] == TRUE) {
    return(1)
  } else{
    return(1 + count_nodes(tree['left']) + count_nodes(tree['right']))    
  }
}

count_nodes(tree)
#> Error in count_nodes(tree["left"]): (list) object cannot be coerced to type 'logical'

使用双括号可以解决问题。

count_nodes <- function(tree){
  if(tree[['is_leaf']]) {
    return(1)
  } else{
    return(1 + count_nodes(tree[['left']]) + count_nodes(tree[['right']]))    
  }
}

count_nodes(tree)
#> [1] 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-12
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2016-09-30
    • 2012-01-17
    • 1970-01-01
    相关资源
    最近更新 更多