以下代码尝试构建一个简单的二叉树。非叶节点包含左子节点Lchild'和一个正确的孩子' Rchild'叶节点不包含任何内容。这段代码的问题在于,添加变量&root;' root'但是没有改变任何东西(细节参考代码中的评论)将改变' BiTree'的结果。代码是可执行的。结果BiTree[[2]]
在调用或不调用' root'。
## rm(list=ls()) ## ANTI-SOCIAL
set.seed(1234)
##this part generate dataset
numVar <- 40 ##number of variables
numSamples <- 400 ##number of samples
Class <- sample(c(0,1), replace = 1, numSamples) ##categorical outcome as '0' or '1'
predictor <- matrix( sample(c(-1,0,1), replace=1, numSamples*numVar), ncol=numVar)
data <- data.frame(predictor, Class)
##BiTree is a list storing a nodes information, reprenting a tree, defined as global
BiTree <- array( list(NULL), dim = 15 )
##set i as global variable to store the ID of each node on the tree, defiend as global
i <- 1
##function to create a tree
##parameter 'root' is the ID of root node for each sub-tree
createTree <- function( data, root )
{
##stop grow the sub-tree if data size is smaller than 10
if( (nrow(data) <= 10 ) ) { i <<- i + 1; return(); }
##seperate the data into two parts to grow left-sub-tree and right-sub-tree
index.P1 <- 1:floor( nrow( data )/2 )
index.P2 <- !index.P1
data.P1 <- data[ index.P1, ]
data.P2 <- data[ index.P2, ]
##NOTE HERE: result will differ with or without execute any of the following call of root
##root
##cat(root)
##print(root)
##i records the ID of node in the tree. it increments after one new node is added to the tree
i <<- i + 1
##record node ID for left child of the root
BiTree[[ root ]]$Lchild <<- i
##create left branch
createTree( data.P1, i )
##record node ID for right child of the root
BiTree[[ root ]]$Rchild <<- i
##create right branch
createTree( data.P2, i )
}
createTree( data, 1 )
##look at the second node on the tree, which will differ
(BiTree[[2]])