繁体   English   中英

function 创建后序二叉树数组

[英]function to create array of post order binary tree

我试图创建一个递归的 function,它从给定的树中创建一个后序整数数组。 这是代码:

//structure
typedef struct node
{
    // Each node holds a single integer.
    int data;

    // Pointers to the node's left and right children.
    struct node *left, *right;
} node;

// preorder_recursive is same as postorder_recursive(), except
// array[i] comes before the recursive calls

int *postorder_recursive(node *root)
{
    int *array = malloc(sizeof(node) * node_count(root)); // node_count(root) counts nodes in binary tree
    int i = 0;
    if (root == NULL)
        return 0;

    while (root != NULL)
    {
        postorder_recursive(root->left);
        postorder_recursive(root->right);
        array[i] = root->data;
        i++;
    }
    return array;
}

// returns 1 if pre order = post order, returns 0 otherwise
int compare(node *a, node *b)
{
    int i = 0;
    int *preArray, *postArray;
    if (node_count(a) != node_count(b))
        return 0;
    preArray = preorder_recursive(a);
    postArray = postorder_recursive(b);
    for (i = 0; i < node_count(a); i++)
    {
        if (preArray[i] != postArray[i])
            return 0;
    }

  free(preArray);
  free(postArray);

    return 1;
}

我不确定错误是否在这个 function 中,但如果是,则可能是由于 while 循环。 任何帮助都会很棒。

编辑:我包含了更多代码。 这样做的目的是将后序数组与前序数组进行比较。

您的 function postorder_recursive postorder_recursive()每次调用时都会创建一个新数组。 此外, while(root != NULL)将永远循环非空树,如果不是因为它写入array末尾并在某些时候导致分段错误。

解决方案是将 function 拆分为创建数组的一个,然后将另一个 function 递归填充数组,如下所示:

static size_t postorder_recursive(const node *root, int *array, size_t index) {
    if (root == NULL)
        return index;

    index = postorder_recursive(root->left, array, index);
    index = postorder_recursive(root->right, array, index);
    array[index++] = root->data;

    return index;
}

int *postorder_to_array(const node *root)
{
    int *array = malloc(sizeof(node) * node_count(root));
    postorder_recursive(root, array, 0);
    return array;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM