交换左右子树
设树B是一棵采用链式结构存储的二叉树,编写一个把树B中所有节点的左右子树进行交换的函数
算法思想
采用递归算法实现交换二叉树的左右子树,首先交换root节点左孩子的左右子树,然后交换root节点右孩子的左右子树,最后交换root节点的左右孩子,当节点为空时递归结束(后序遍历思想)
void swap(BTNode root)
{
if (root)
{
swap(root->left);
swap(root->right);
temp = root->left;
root->left = root->right;
root->left = temp;
}
}
非递归交换左右子树
算法思想
- 初始化栈:将根节点入栈。
- 遍历节点:
- 弹出栈顶节点。
- 交换该节点的左右子树。
- 将右子树(若存在)入栈。
- 将左子树(若存在)入栈。
- 结束条件:栈为空,遍历结束。
- 结果:树的所有节点的左右子树被交换。
// 定义二叉树节点
typedef struct BTNode
{
int data;
struct BTNode* left;
struct BTNode* right;
} BTNode;
// 交换左右子树
void SwapChildren(BTNode* node)
{
BTNode* temp = node->left;
node->left = node->right;
node->right = temp;
}
// 辅助函数:创建新节点
BTNode* CreateNode(int data)
{
BTNode* newNode = (BTNode*)malloc(sizeof(BTNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 辅助函数:中序遍历
void InOrderTraversal(BTNode* root)
{
if (root == NULL)
return;
InOrderTraversal(root->left);
printf("%d ", root->data);
InOrderTraversal(root->right);
}
// 非递归交换二叉树所有节点的左右子树
void SwapBinaryTree(BTNode* root)
{
if (root == NULL)
return;
StackNode* stack = NULL;
Push(&stack, root);
while (!IsEmpty(stack))
{
BTNode* current = Pop(&stack);
// 交换当前节点的左右子树
SwapChildren(current);
// 如果右子树存在,入栈
if (current->right)
{
Push(&stack, current->right);
}
// 如果左子树存在,入栈
if (current->left)
{
Push(&stack, current->left);
}
}
}