该代码片段是根据其前序和中序表示重建二叉树。
static public BinaryTreeNode<T> BuildFromPreAndInOrder<T>(ReadOnlySpan<T> preOrder, ReadOnlySpan<T> inOrder)
{
if (preOrder == null || preOrder.IsEmpty || inOrder == null || inOrder.IsEmpty) { return null; }
var val = preOrder[0];
BinaryTreeNode<T> root = new BinaryTreeNode<T>(val);
// this doesn't make sense
var splitPoint = MemoryExtensions.IndexOf<T>(inOrder, val);
if (splitPoint == -1) {
return null;
}
preOrder = preOrder.Slice(1);
var leftPart = inOrder.Slice(0, splitPoint);
var rightPart = inOrder.Slice(splitPoint + 1);
root.left = BuildFromPreAndInOrder(preOrder, leftPart);
root.right = BuildFromPreAndInOrder(preOrder, rightPart);
return root;
}
该节点很简单,所以我附上部分内容。
class BinaryTreeNode<T> : IEquatable<BinaryTreeNode<T>>
{
public T key;
public BinaryTreeNode<T> left;
public BinaryTreeNode<T> right;
}
我尝试在 .NET Core 3 Preview 7 SDK 上编译它,但编译器抱怨error CS1503: Argument 2: cannot convert from 'T' to 'System.ReadOnlySpan<T>'。为什么编译器不能选择正确的方法?检查工具向我显示了一个应该能够与此匹配的签名。
public static int IndexOf<T>([NullableAttribute(new[] { 0, 1 })] this ReadOnlySpan<T> span, [NullableAttribute(1)] T value) where T : IEquatable<T>;
慕少森
相关分类