-1

我们如何使用中序遍历将树的元素存储在数组中?我读到有人说将父索引存储在 i 和左子 2*i+1 和右 ar 2*i+2 。但这对我不起作用?需要帮助 :)

4

1 回答 1

1

假设它是一棵二叉树,这里是一个伪代码

tree_to_array(tree, array, index)
    if tree != NULL then
        // stores recursively all the elements on the left
        index = tree_to_array(tree.left, array, index)
        // the root of the (sub)tree
        array[index] = tree
        // stores recursively all the elements on the right
        return tree_to_array(tree.right, array, index + 1)
    return index
于 2013-09-26T07:35:17.193 回答