问题
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 .
回答1:
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);
}
来源:https://stackoverflow.com/questions/43774655/how-can-i-get-the-parent-in-binary-tree