假设节点类定义为:
public class Node
{
public Node Left { get; set; }
public Node Right { get; set; }
public int Value { get; set; }
public Node(int value)
{
Value = value;
}
}
您可以在以下两种方法添加到这个类来实现你想要做什么:
public Node GetSubtree(int value, int depth)
{
int foundDepth;
return GetSubtreeHelper(value, depth, out foundDepth);
}
private Node GetSubtreeHelper(int value, int depth, out int foundDepth)
{
if (Value == value)
{
foundDepth = 0;
return depth == foundDepth ? this : null;
}
if (Left != null)
{
var node = Left.GetSubtreeHelper(value, depth, out foundDepth);
if (foundDepth != -1)
{
return ++foundDepth == depth ? this : node;
}
}
if (Right != null)
{
var node = Right.GetSubtreeHelper(value, depth, out foundDepth);
if (foundDepth != -1)
{
return ++foundDepth == depth ? this : node;
}
}
foundDepth = -1;
return null;
}
测试此使用树在你的问题:
GetSubtree(15, 0) = Node 15
GetSubtree(15, 1) = Node 7
GetSubtree(15, 2) = Node 3
GetSubtree(15, 3) = Node 1
GetSubtree(15, 4) = null
你指的是BST,还是只是一个二叉树?无论哪种方式,它都应该很容易。真正的问题是:如何找到节点的第N个父节点?该节点是您正在查找的子树。你会如何找到节点的直接父节点? – Kobi
我指的是BST。但是哪个遍历方法对于找到这个第N个父节点非常有用。或者你有任何算法? –
没有人能在上面给出的库中添加一个函数来满足我的要求吗? –