微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我有序和有序的树如何生成此的数组表示

如何解决我有序和有序的树如何生成此的数组表示

考虑下面的二进制搜索

     a
    /  \
   b    c
  /      \
 d        e

预订为a b d c e
依次为d b a c e
并且数组表示形式为a b c d \0 \0 e

现在的问题是

给出了树的根,我可以使用以下代码从该根生成预序和顺序

void preorder(struct node *root){
    if(root==NULL){
        return;
    }

    printf("%d\n",root->data);
    preorder(root->left);
    preorder(root->right);

}

void inorder(struct node *root){
    if(root==NULL){
        return;
    }

    
    inorder(root->left);
    printf("%d\n",root->data);
    inorder(root->right);

}

现在我可以将此预购和订购存储在数组中。并从这两个数组中..我想要BST的数组表示形式

解决方法

数组索引的计算方式如下:

Root->arrayIndex = 0

LeftChild->arrayIndex = 2 * parentNode->arrayIndex + 1
RightChild->arrayIndex = 2 * parentNode->arrayIndex + 2

为简单起见,假设您已经知道结果数组的大小(如果不是,则很容易计算)。

char array[ARRAY_SIZE];
memset(array,'\0',ARRAY_SIZE);  // Fill the whole array with \0

现在,您要用树中的值覆盖一些数组元素。可以通过以下方式完成:

void fill_array(struct node *root,char* array,int index){
    if(root==NULL){
        return;
    }

    array[index] = root->data;
    fill_array(root->left,array,2*index + 1);
    fill_array(root->right,2*index + 2);
}

并这样称呼它:

struct node *root = ROOT_OFTHE_TREE;

char array[ARRAY_SIZE];
memset(array,ARRAY_SIZE);  // Fill the whole array with \0

fill_array(root,0);

// Add code to print the array

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。