我想将二叉树中的每个节点与负值-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/