c - 二叉树中的负数

标签 c binary-tree

我想将二叉树中的每个节点与负值-2相乘。但我不知道如何实现。当与负数相乘时,左右子树会改变它们的位置。我被困在这样做。

 typedef struct BTree {
    int value;
    struct BTree *left, *right;
} BTree;

BTree *insert(BTree *root, int value) {
    if (root == NULL) {
        BTree *new_node = (BTree*) malloc(sizeof(BTree));
        new_node->value = value;
        new_node->left = new_node->right = NULL;
        return new_node;
    }
    if (value < root->value) {        
        root->left = insert(root->left, value);
    }
    else if (value > root->value) {   
        root->right = insert(root->right, value);
    }
    else {

    }
    return root;
}

void print_tree(BTree *root)
{
    if (root == NULL) return;
    print_tree(root->left);
    printf("%d ", root->value);
    print_tree(root->right);
}



   void swap_tree(BTree *root)  
{ 
  if (root == NULL)  
    return;   
  else 
  { 
    BTree *temp; 

    swap_tree(root->left); 
    swap_tree(root->right); 

    temp        = root->left; 
    root->left  = root->right; 
    root->right = temp; 
  } 
} 

最佳答案

从你的问题来看,你似乎在谈论二叉搜索树而不仅仅是二叉树。正如您正确指出的那样,将二叉搜索树的节点中的所有值相乘将导致更改每个节点处子树的顺序。如何实现这一点取决于您正在使用的树表示形式,但对于大多数基于递归的方法(从叶子开始交换每个节点上的两个子节点)应该可行。

关于c - 二叉树中的负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53443577/

相关文章:

c - C 中的二叉搜索树中的词频?

C 凯撒密码错误随机字符串输出

c - 如何释放结构中的动态二维数组?

c - 在不同的 C 文件中使用函数

c - 未定义引用 'timer_create ' C 的信号

java - 打印树程序

捕获分段违规并继续生活

c++ - 有可能进行高效的基于指针的二进制堆实现吗?

python - 有多少种方法可以构建完美平衡的树?

c++ - 二叉树遍历以枚举斐波那契值的所有排列