【问题标题】:function to create array of post order binary tree创建后序二叉树数组的函数
【发布时间】:2021-02-27 00:46:46
【问题描述】:

我正在尝试创建一个递归函数,该函数从给定的树创建一个后序整数数组。这是代码:

//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;
}

我不完全确定错误是否在此函数中,但如果是,则可能是由于 while 循环。任何帮助都会很棒。

编辑:我已经包含了更多的代码。这样做的目的是比较一个后序数组和一个前序数组。

【问题讨论】:

  • 我们需要更多代码,比如你的结构什么的

标签: c recursion binary-tree postorder


【解决方案1】:

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

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

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2016-02-24
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多