0

How can i get the Parent in Binary tree in this code ?

I wrote this :

public class Node
{
    public string state;
    public Node Left;
    public Node Right;




    public Node (string s , Node L , Node R )
    {
        this.state = s;
        this.Right = R;
        this.Left = L;
    }

    public Node (string s)
    {
        this.state = s;
        this.Right = null;
        this.Left = null;
    }


}

And code this for tree of some data :

1

2

Now , how can i get the parent of Node like ( new Node("22lltrk", null, null) ) what i need to add to my code and where ?

thanks .

  • Please show what code you tried in order to solve your problem. Showing just initialization data of the tree isn't relevant code – Gilad Green May 04 '17 at 05:39
  • Found this on first search http://stackoverflow.com/questions/30736577/find-the-parent-node-of-a-node-in-binary-search-tree – Ali Niaz May 04 '17 at 05:46

1 Answers1

2

Opt 1: add a parent link to your class

public class Node 
{
    public string state;
    public Node Left;
    public Node Right;
    public Node Parent; // new

    public Node (string s , Node L , Node R )
    {
        this.state = s;
        this.Right = R;
        this.Right.Parent = this; // new
        this.Left = L;
        this.Left.Parent = this; // new
    }

    public Node (string s)
    {
        this.state = s;
        this.Right = null;
        this.Left = null;
        this.Parent = null; // new
    }
}

Opt 2: Tree traversal

Node FindParent(Node root, Node child)
{
   // Base Cases
   if(root.Left == null && root.Right == null)
    return null;

   if(root.Left == child || root.Right == child)
    return root;

   // Recursion
   var leftSearch = FindParent(root.Left, child);
   if (leftSearch != null)
       return leftSearch;

   return FindParent(root.Right, child);
}
Prateek Arora
  • 274
  • 2
  • 6