且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何在二叉树中获取父级

更新时间:2023-01-17 20:02:36

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

选择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);
}