交换二叉树的左右子树c语言
时间: 2023-03-31 16:03:28 浏览: 105
二叉树的左右子树交换(C++)
5星 · 资源好评率100%
可以使用递归或迭代的方式交换二叉树的左右子树。具体实现方法如下:
递归方法:
void invertTree(struct TreeNode* root){
if(root == NULL){
return;
}
struct TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
}
迭代方法:
void invertTree(struct TreeNode* root){
if(root == NULL){
return;
}
struct TreeNode* temp;
struct TreeNode* node;
struct TreeNode* queue[100];
int front = , rear = ;
queue[rear++] = root;
while(front != rear){
node = queue[front++];
temp = node->left;
node->left = node->right;
node->right = temp;
if(node->left != NULL){
queue[rear++] = node->left;
}
if(node->right != NULL){
queue[rear++] = node->right;
}
}
}
阅读全文