采用二叉链表存储结构,交换二叉树中每个结点的左孩子和右孩子。
时间: 2023-11-14 13:05:45 浏览: 101
交换二叉树中每个结点的左孩子和右孩子可以通过递归实现。具体步骤如下:
1. 如果当前结点为空,返回空。
2. 交换当前结点的左孩子和右孩子。
3. 递归交换当前结点的左子树。
4. 递归交换当前结点的右子树。
5. 返回交换后的二叉树。
具体代码实现如下:
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def swap_tree(root: Node) -> Node:
if not root:
return None
# 交换左右子树
root.left, root.right = root.right, root.left
# 递归交换左子树
swap_tree(root.left)
# 递归交换右子树
swap_tree(root.right)
return root
```
以上代码中,我们定义了一个`Node`类表示二叉树的一个结点,其中`val`表示结点的值,`left`和`right`分别表示左孩子和右孩子。`swap_tree`函数接受一个二叉树的根结点作为参数,返回交换后的二叉树的根结点。在函数中,我们首先判断当前结点是否为空,如果是,则返回空。接着,我们交换当前结点的左孩子和右孩子。然后,我们分别递归交换当前结点的左子树和右子树。最后,我们返回交换后的二叉树的根结点。
相关问题
采用二叉链表存储结构,交换二叉树中每个结点的左孩子和右孩子。代码实现
以下是采用二叉链表存储结构,交换二叉树中每个结点的左孩子和右孩子的代码实现:
```C++
#include <iostream>
using namespace std;
// 二叉树结点的定义
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 交换二叉树中每个结点的左孩子和右孩子的函数
void swapTree(TreeNode* root) {
if (root == NULL) {
return;
}
swap(root->left, root->right); // 交换当前结点的左右孩子
swapTree(root->left); // 递归交换左子树中的结点
swapTree(root->right); // 递归交换右子树中的结点
}
// 中序遍历二叉树的函数(用于测试交换后的结果)
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
int main() {
// 构造二叉树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
cout << "原始二叉树:";
inorderTraversal(root); // 中序遍历原始二叉树
cout << endl;
swapTree(root); // 交换二叉树中每个结点的左孩子和右孩子
cout << "交换后的二叉树:";
inorderTraversal(root); // 中序遍历交换后的二叉树
cout << endl;
return 0;
}
```
运行结果:
```
原始二叉树:4 2 5 1 6 3 7
交换后的二叉树:7 3 6 1 5 2 4
```
采用二叉链表存储结构,交换二叉树中每个结点的左孩子和右孩子的完整代码
这里提供一个递归实现的代码:
```
void swapTree(TreeNode* root) {
if (root == nullptr) {
return;
}
swap(root->left, root->right);
swapTree(root->left);
swapTree(root->right);
}
```
其中,`TreeNode` 是二叉树结点的结构体,包含 `left` 和 `right` 指针分别指向左孩子和右孩子。
该函数通过递归的方式,依次交换每个结点的左右孩子。在交换左右孩子之后,分别对左子树和右子树递归调用 `swapTree()` 函数,完成整个二叉树的左右孩子交换。
阅读全文
相关推荐












