evolve75/RubyTree

Get Node Path

MZic opened this issue · 4 comments

MZic commented

Hi All,

During my work I needed to retrieve the path for some nodes so i've implemented the following code:

class Tree::TreeNode
  def path_as_string(separator)
    get_path_array().reverse.join(separator)
  end

  def path_as_array()
    get_path_array().reverse
  end

  def get_path_array(current_array_path = [])
    path_array = current_array_path + [name]
    if !parent
      return path_array
    else
      path_array=parent.get_path_array(path_array)
      return path_array
    end
  end
end

I though it may be useful for someone else to have something similar.
Thanks

@MZic

Thanks a lot for sharing this. Would you be able to also attach a short test case for the code above?

MZic commented

I tried to keep the same structure you have in other tests. Anyway i've also opened a PR #49 if you like.

    # Test the path_as_string method.
    def test_path_as_string
      j = Tree::TreeNode.new("j")
      f = Tree::TreeNode.new("f")
      k = Tree::TreeNode.new("k")
      a = Tree::TreeNode.new("a")
      d = Tree::TreeNode.new("d")
      h = Tree::TreeNode.new("h")
      z = Tree::TreeNode.new("z")
      p = Tree::TreeNode.new("p")
      t = Tree::TreeNode.new("t")
      e = Tree::TreeNode.new("e")

      # Create the following Tree
      #        j         <-- level 0 (Root)
      #      /   \
      #     f      k     <-- level 1
      #   /   \      \
      #  a     h      z  <-- level 2
      #   \   / \
      #    d p   t       <-- level 3
      #   /
      #  e               <-- level 4
      j << f << a << d << e
      f << h
      h << p
      h << t
      j << k << z

      assert_equal(t.path_as_string(' => '), 'j => f => h => t')
      assert_equal(z.path_as_string(' => '), 'j => k => z')
      assert_equal(a.path_as_string(' => '), 'j => f => a')
    end

    # Test the path_as_array method.
    def test_path_as_array
      j = Tree::TreeNode.new("j")
      f = Tree::TreeNode.new("f")
      k = Tree::TreeNode.new("k")
      a = Tree::TreeNode.new("a")
      d = Tree::TreeNode.new("d")
      h = Tree::TreeNode.new("h")
      z = Tree::TreeNode.new("z")
      p = Tree::TreeNode.new("p")
      t = Tree::TreeNode.new("t")
      e = Tree::TreeNode.new("e")

      # Create the following Tree
      #        j         <-- level 0 (Root)
      #      /   \
      #     f      k     <-- level 1
      #   /   \      \
      #  a     h      z  <-- level 2
      #   \   / \
      #    d p   t       <-- level 3
      #   /
      #  e               <-- level 4
      j << f << a << d << e
      f << h
      h << p
      h << t
      j << k << z

      assert_equal(e.path_as_array, ['j', 'f', 'a', 'd', 'e'])
      assert_equal(p.path_as_array, ['j', 'f' , 'h', 'p'])
      assert_equal(k.path_as_array, ['j', 'k'])
    end

@MZic,

Thanks for the test case. I will incorporate your changes in the next release.

Merged into Release R0.9.5 in commit a2a27ea.