创建一个数组,其中包含一个级别的节点值

时间:2017-08-06 14:34:14

标签: c data-structures tree binary-tree

我必须创建一个数组,其中包含作为参数传递的级别中的节点值。函数createArray必须返回一个数组,该数组包含作为参数传递的级别的节点值。我的代码是:

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>

struct node {
    int data;
    struct node* left;
    struct node* right;
};

struct node* newNode(int data) {
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return node;
}

int numNodesLevel(struct node* root, int level) {
    if (root == NULL) {
        return 0;
    }
    else {
        if (level == 0) {
            return 1;
        }
        return numNodesLevel(root->left, level - 1) + numNodesLevel(root->right, level - 1);
    }
}

int max(int a, int b) {
    if(a > b) {
        return a;
    }
    else {
        return b;
    }
}

int height(struct node* root) {
    if (root == NULL) {
        return -1;
    }
    else {
        if (root->left == NULL && root->right == NULL) {
            return 0;
        }
        return max(height(root->left), height(root->right)) + 1;
    }
}

int maxNodesLevel(struct node* root) {
    if (root == NULL) {
        return 0;
    }
    else {
        int max = 0;
        int h = height(root);
        int i = 0;
        for (i = 0; i <= h; i++) {
            if (numNodesLevel(root, i) > max) {
                max = numNodesLevel(root, i);
            }
        }
        return max;
    }
}

void fill(struct node* root, int* A, int level, int* i) {
    if (root != NULL) {
        if (level == 0) {
            A[*i] = root->data;
            *i = *i + 1;
        }
        fill(root->left, A, level - 1, i);
        fill(root->right, A, level - 1, i);
    }
}

int* createArray(struct node* root, int level) {
    if (root != NULL) {
        int *A = (int*)calloc(maxNodesLevel(root), sizeof(int));
        int i = 0;
        fill(root, A, level, &i);
        return A;
    }
}

int main(){
    struct node* root = newNode(12);
    root->left = newNode(3);
    root->right = newNode(16);
    root->left->left = newNode(2);
    root->left->right = newNode(2);
    root->right->left = newNode(2);
    root->right->right = newNode(22);
    printf("%d", createArray(root,1));
    getchar();
    return 0;
}

结果应该是3,16,这是1级节点的值,但它给了我不同的数字,如22721648.每次运行代码时这些数字都不同,所以我认为一定有问题我使用指针的方式,但我无法弄清楚错误在哪里。 有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

代码是正确的,但这里唯一的错误是createArray()返回一个数组,你将它视为int。 添加以下代码而不是printf(),它将起作用。

int level = 1, *arr;
arr = createArray(root, level);
for(int i = 0; i < 2 * level; i++){
    printf("%d ", arr[i]);
}

希望它会有所帮助!!