R - 计算二叉树中的节点时出错:( list)对象无法强制键入'logical'

时间:2018-02-09 18:04:31

标签: r count tree binary-tree nodes

我有一个结构如下的二叉树:

> 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"))
> 

请帮忙解决此问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

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

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

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