How can i get the Parent in Binary tree

可紊 提交于 2021-02-20 05:15:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!