# help! about Binary Tree function

I am struggling in writing a method to return the parent node of a given Tree node. The class of the Tree is following:

class BinaryTree {
private:
int data;
BinaryTree *left;
BinaryTree *right;
public:
BinaryTree(int i, BinaryTree *L, BinaryTree *R) {
data=i; left=L; right=R;
}
~BinaryTree() {}
int RootData() { return data; }
BinaryTree* Left() { return left; }
BinaryTree* Right() { return right;}
};

The problem is that I need to write a member function which takes a Tree Node argument and returns the parent node of that node.

Thanks very much!

• [b][red]This message was edited by tom_sw at 2003-11-3 10:45:12[/red][/b][hr]
: I am struggling in writing a method to return the parent node of a given Tree node. The class of the Tree is following:
:
: class BinaryTree {
: private:
: int data;
: BinaryTree *left;
: BinaryTree *right;
: public:
: BinaryTree(int i, BinaryTree *L, BinaryTree *R) {
: data=i; left=L; right=R;
: }
: ~BinaryTree() {}
: int RootData() { return data; }
: BinaryTree* Left() { return left; }
: BinaryTree* Right() { return right;}
: };
:
: The problem is that I need to write a member function which takes a Tree Node argument and returns the parent node of that node.
:
: Thanks very much!
:
Given what you've described here, this is not possible, since the individual node doesn't know it's parent. There are 2 ways to approach this, but both require additional information that is not presented here.

One way is to include a parent pointer in the class - that is set to the parent as the node is inserted into the structure. This means that the basic class structure needs to be changed as well as the insertion algorithm.

The other way is to start at the root of the tree and search through each node until one of the child nodes matches the node in question - the node that contains that pointer is then the parent. This requires access to the root pointer - which could be added as a static variable of the class, set with the first node, or if the root ever changes - then addition of a method to perform the search.