交换二叉树的左右子树c语言
时间: 2023-03-31 16:03:28 浏览: 113
可以使用递归或迭代的方式交换二叉树的左右子树。具体实现方法如下:
递归方式:
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** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*)*100);
int top = -1;
stack[++top] = root;
while(top >= ){
struct TreeNode* node = stack[top--];
temp = node->left;
node->left = node->right;
node->right = temp;
if(node->left != NULL){
stack[++top] = node->left;
}
if(node->right != NULL){
stack[++top] = node->right;
}
}
free(stack);
}
阅读全文