From: Eric Hodel Date: 2011-07-22T08:37:24+09:00 Subject: Re: Building a tree from the leaves down On Jul 21, 2011, at 8:21 AM, Intransition wrote: > Basic example, let's use this class: > > class CaseObject > attr :case > def initialize(parent_case) > @case = parent_case > end > end > > And this has been defined: > > c1 = CaseObject.new(nil) > c11 = CaseObject.new(c1) > c12 = CaseObject.new(c1) > c121 = CaseObject.new(c12) > c122 = CaseObject.new(c12) > d1 = CaseObject.new(nil) > d11 = CaseObject.new(d1) > d12 = CaseObject.new(d1) This is already a tree. > Then I am given all the _leaf_ nodes in a list: > > [c11, c121, c122, d11, d12] You won't need to rebuild the original tree if you have bidirectional links. class CaseObject def initialize parent @case = parent @children = [] parent.add self if parent end def add child @children << child end end Walking the tree up or down is simple when you can walk both up and down so the exercise is left to the reader. Also, there's no relationship between the d nodes and the c nodes.