c - 数组排列、二叉树、回溯

标签 c algorithm binary-tree

我想编写一个函数,按以下方式排列数组。 给定一个像这样的二叉树(十六进制以保持对称性):

 0
        1
    2       3
  4   5   6   7
 8 9 A B C D E F

我想按照回溯算法得到数字:

[0,1,2,4,8,9,5,A,B,3,6,C,D,7,E,F]

我已经写了一个 C 函数,但我确信有一种更干净/更快的递归方法可以做到这一点。这是我的代码:

void bin_perm(float* data, float* bprm, size_t size) {
    bprm[0] = data[0];
    size_t j = 1;
    size_t i = 1;
    while (j < size) {
        while (i < size) {
            bprm[j++] = data[i];
            i *= 2;
        }
        i = i / 2 + 1;
        while (i % 2 == 0) {
            i /= 2;
        }
    }
}

最佳答案

void bin_perm_recur(float* data, size_t data_idx, float* bprm, size_t* bprm_idx_ptr, size_t size)
{
    bprm[(*bprm_idx_ptr)++] = data[data_idx];
    if (data_idx * 2 < size)
        bin_perm_recur(data, data_idx * 2, bprm, bprm_idx_ptr, size);
    if (data_idx * 2 + 1 < size)
        bin_perm_recur(data, data_idx * 2 + 1, bprm, bprm_idx_ptr, size);
}

void bin_perm(float* data, float* bprm, size_t size)
{
    bprm[0] = data[0];
    size_t j = 1;
    bin_perm_recur(data, 1, bprm, &j, size);
}

关于c - 数组排列、二叉树、回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19878201/

相关文章:

c - 无法在 ubuntu 中的 C 程序中包含 'sqlite3'

arrays - 算法:找到包含 K 个 0's in array of 1' 和 0 的最小连续数组

algorithm - 无死锁与无饥饿

data-structures - 时间序列数据的最佳数据结构

Java : Bound mismatch: is not a valid substitute for the bounded parameter <E extends Comparable<E>>

c - 在 case 外部声明变量

c - 为什么新字符串上的 strcat() 在开始时会抛出未定义的字符,而 strcpy 没问题?

c - 你如何在 C 中无限期地保持套接字连接打开?

algorithm - 无序列表中的第 K 个元素,使用 k 顺序统计 - 时间复杂度 O(n)?

algorithm - 使用 +、- 运算符平衡算术表达式树