【问题标题】:Storing BinarySearchTree inOrder traversal in an array将 BinarySearchTree 按顺序遍历存储在数组中
【发布时间】:2017-01-18 14:38:30
【问题描述】:

我参考了以下链接,看看如何将 inOrder 遍历保存到数组 Binary Search Tree to inOrder Array

我的树:

       100
      /  \
    50    300
   / \
  20  70

当第一个元素 (20) 被插入到数组中时,索引值增加为 1。现在,当控制去获取下一个节点 (50) 时,索引值变为 0。

代码:

storeInOrder(root1,arr1,0);

private static void storeInOrder(Node root1, int[] arr1, int index) {       
    if(root1 == null){return;}

    storeInOrder(root1.left, arr1,index);       
    arr1[index++] = root1.data;
    storeInOrder(root1.right,arr1,index);
}

数组中的预期输出:20 50 70 100 300
我得到的输出为 100 300 0 0 0

【问题讨论】:

  • 你用什么语言写这个?您的 index 参数似乎不是通过引用传递的。
  • @TeddySterne 我正在用 Java 编写代码

标签: arrays binary-search-tree inorder


【解决方案1】:

您可以修改函数以返回上次使用的索引,然后根据新索引进行更新。

storeInOrder(root1,arr1);

private static void storeInOrder(Node root1, int[] arr1) {
    storeInOrderRecursive(root1,arr1,0);
}

private static Integer storeInOrderRecursive(Node root1, int[] arr1, int index) {       
    if(root1 == null){return index;}

    index = storeInOrderRecursive(root1.left, arr1,index);       
    arr1[index++] = root1.data;
    storeInOrderRecursive(root1.right,arr1,index);

    return index;
}

包装函数不是必需的,但由于您总是将 0 传递给 storeInOrderRecursive,这使得 API 相似,然后返回值仍然可以是 void 以调用 storeInOrder

【讨论】:

  • 函数storeInOrderRecursive将其返回类型声明为Integer,但没有返回值。
【解决方案2】:

将逻辑放在访问代码中的想法是正确的,但是你需要一个全局索引。在您的实现中,您修改的索引是按值传递的,这不会导致所需的行为,因为仅更改了值的本地副本。 Java 中的公式可能如下所示。

int[] iArray; // initialize with the desired size
int GlobalIndex = 0;

void Visit(Node iNode)
{
    iArray[GlobalIndex++] = iNode.Data;
}

void StoreInOrder(Node iRoot)
{       
    if(null != iRoot)
    {
        StoreInOrder(iRoot.Left);       
        Visit(iRoot);
        StoreInOrder(iRoot.Right);
    }
}

或者,以更接近原始问题的更简洁的形式。

int[] iArray; // initialize with the desired size
int GlobalIndex = 0;

void StoreInOrder(Node iRoot)
{       
    if(null != iRoot)
    {
        StoreInOrder(iRoot.Left);
        iArray[GlobalIndex++] = iNode.Data;
        StoreInOrder(iRoot.Right);
    }
}

如果实现必须尽可能接近原始版本,可以使用以下版本。它使用int 的包装类作为引用调用的替代品,因为Java 不允许对基本数据类型进行引用调用。

class IntWrapper
{
    public int Value;
    public IntWrapper(int InitialValue)
    {
        Value = InitialValue;
    }
}

int[] iArray;

StoreInOrder(iRoot, iArray, new IntWrapper() )

void StoreInOrder(Node iRoot, int[] iArray, IntWrapper Index)
{
    StoreInOrder(iRoot.Left,iArray,Index);
    iArray[Index.Value++] = iNode.Data;
    StoreInOrder(iRoot.Right,iArray,Index);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多