views:

181

answers:

2

I have an own Tree object implemented in PHP. Say we have a tree like:

Root  
|_ Folder 1  
|_ Folder 2  
   |_ Subfolder 1

I can access Subfolder 1 like this:

$sf1 = $Tree->NavigateTo("Folder 2/Subfolder 1")

And $sf1 will hold the Subfolder 1 node. I want to implement a GetParentNode() method, so that

$parent = $sf1->GetParentNode()  // Equivalent to Folder 2

This is the Tree definition:

class JaxpTree
{
    /**
     * @var     JaxpTree|JaxpTreeNode    Array of Tree nodes.
     * @access  public
     */
    public $Nodes;

    /**
     * @var     JaxpList    Array of Tree items.
     * @access  public
     */
    public $ItemList;
}

It works by nesting Tree objects, so Subfolder 1 can be accessed also like:

$Tree->Nodes["Folder 2"]->Nodes["Subfolder 1"]

which will be a TreeNode object:

/**
 * Represents a Tree node.
 *
 * @package     Jaxp.Trees
 * @subpackage  TreeNode
 * @since       1.0
 */

class JaxpTreeNode
{
    /**
     * @var     int Node id.
     * @access  public
     */
    public $Id;

    /**
     * @var     JaxpTreeNodeAttributes  Contains the node's attributes.
     * @access  public
     */
    public $Attributes;
}

How can I implement parent node accessing here?

Solved

Solution is to add a Parent property which contains a reference to the parent node. Thanks!

A: 

You have to pass a reference of the parent to the node.

Otto Allmendinger
So, I should add a "Parent" property with the reference.
Joel Alejandro
@Joel yes, exactly
Otto Allmendinger
A: 

You need to store the parent node for every node (except the root node that has no parent node).

So just add an parent attribute to your JaxpTreeNode that holds the parent node or null if it’s the root node.

Gumbo