【发布时间】: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