2017-05-04 74 views
0

我怎样才能在此代码中的二进制树中的父?我怎样才能得到在二进制树中的父

我写了这个:

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; 
    } 


} 

和代码这对某些数据的树:

1

2

现在,我怎么能得到节点像父(新的节点(“22lltrk”,null,null)) 我需要添加到我的代码和哪里?

谢谢。

+0

请出示你为了解决您的问题,试了一下代码。只显示树的初始化数据是不相关的代码 –

+0

在第一次搜索时发现此问题http://stackoverflow.com/questions/30736577/find-the-parent-node-of-a-node-in-binary-search-树 –

回答

1

选项1:添加一个父链接到您的类

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 
    } 
} 

选项2:树的遍历

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); 
} 
+1

感谢您的解释 – amr2312345