在数组中存储BinarySearchTree inOrder遍历

时间:2017-01-18 14:38:30

标签: arrays binary-search-tree inorder

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

我的树:

open(FH,'<','log_file.txt') or die $!;  # open file
for (;;) {
    while (my $row = <FH>) {
    chomp $row;
    print "$row\n";
    }
    sleep 1;
    seek FH, 0, 1;
}

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

代码:

       100
      /  \
    50    300
   / \
  20  70

阵列中的预期输出:20 50 70 100 300
 我的输出为100 300 0 0 0

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

将逻辑放在访问代码中的想法是正确的,但您需要一个全局索引。在您的实现中,您修改的索引按值传递,这不会导致所需的行为,因为只会更改值的本地副本。 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);
}