C# 如何在二叉树中获取父级
在这段代码中,如何获得二叉树中的父级 我写道:C# 如何在二叉树中获取父级,c#,algorithm,binary-tree,C#,Algorithm,Binary Tree,在这段代码中,如何获得二叉树中的父级 我写道: 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 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;
}
}
并为某些数据的树编写以下代码:
现在,我如何获得Node like(新节点(“22lltrk”,null,null))的父节点
我需要在我的代码中添加什么?在哪里
谢谢 Opt 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:向类添加父链接
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);
}
请显示您为解决问题而尝试的代码。仅显示树的初始化数据与代码无关在第一次搜索时找到此代码请显示您尝试了哪些代码来解决您的问题。只显示树的初始化数据是不相关的代码在第一次搜索时发现了这一点谢谢解释谢谢解释