[R] Break during the recursion?
Atte Tenkanen
attenka at utu.fi
Sun Jul 15 21:54:49 CEST 2007
Here is now more elegant function for inorder tree walk, but I still can't save the indexes!? This version now prints them ok, but if I use return, I get only the first v[i].
leftchild<-function(i){return(2*i)}
rightchild<-function(i){return(2*i+1)}
iotw<-function(v,i)
{
if (is.na(v[i])==FALSE & is.null(unlist(v[i]))==FALSE)
{
iotw(v,leftchild(i))
print(v[i]) # return doesn't work here
iotw(v,rightchild(i))
}
}
> iotw(1:11,1)
[1] 8
[1] 4
[1] 9
[1] 2
[1] 10
[1] 5
[1] 11
[1] 1
[1] 6
[1] 3
[1] 7
Yours faithfully ;-)
Atte
----- Original Message -----
From: hadley wickham <h.wickham at gmail.com>
Date: Sunday, July 15, 2007 6:58 pm
Subject: Re: [R] Break during the recursion?
> On 7/15/07, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> > On 15/07/2007 11:36 AM, Atte Tenkanen wrote:
> > >> On 15/07/2007 10:33 AM, Atte Tenkanen wrote:
> > >>>> On 15/07/2007 10:06 AM, Atte Tenkanen wrote:
> > >>>>> Hi,
> > >>>>>
> > >>>>> Is it possible to break using if-condition during the
> recursive> >>>> function?
> > >>>> You can do
> > >>>>
> > >>>> if (condition) return(value)
> > >>>>
> > >>>>> Here is a function which almost works. It is for inorder-
> tree-
> > >>>> walk.
> > >>>>> iotw<-function(v,i,Stack,Indexes) # input: a vector and the
> > >> first
> > >>>> index (1), Stack=c(), Indexes=c().
> > >>>>> {
> > >>>>> print(Indexes)
> > >>>>> # if (sum(i)==0) break # Doesn't work...
> > >>>> if (sum(i)==0) return(NULL)
> > >>>>
> > >>>> should work.
> > >>>>
> > >>>> Duncan Murdoch
> > >>> Hmm - - - I'd like to save the Indexes-vector (in the example
> > >> c(8,4,9,2,10,5,11,1,3)) and stop, when it is ready.
> > >>
> > >> This seems more like a problem with the design of your function
> > >> than a
> > >> question about R. I can't really help you with that, because
> your> >> description of the problem doesn't make sense to me. What
> does it
> > >> mean
> > >> to do an inorder tree walk on something that isn't a tree?
> > >>
> > >> Duncan Murdoch
> > >
> > > The symbols in vector v have been originally derived from
> "tree". See
> > >
> > > http://users.utu.fi/attenka/Tree.jpg
> > >
> > > But perhaps there's another way to do this, for instance by
> using loops and if-conditions?
> >
> > Or perhaps by doing the tree walk on the tree, before you
> collapse it
> > into a vector.
>
> If it's a binary tree with n levels, I think you should be able to
> generate the positions more directly, depending on how the tree has
> been flattened. Binary heaps work this way, so that might be a good
> place to start. See http://en.wikipedia.org/wiki/Binary_heap,
> particularly heap implementation.
>
> Hadley
>
More information about the R-help
mailing list