编写算法交换二叉树中所有结点的左右子树。
时间: 2023-04-19 20:03:50 浏览: 114
算法步骤:
1. 如果二叉树为空,则返回空。
2. 如果二叉树不为空,则交换当前节点的左右子树。
3. 递归交换当前节点的左子树。
4. 递归交换当前节点的右子树。
代码实现:
```
void swapTree(TreeNode* root) {
if (root == nullptr) {
return;
}
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
swapTree(root->left);
swapTree(root->right);
}
```
相关问题
编写算法交换二叉树中所有结点的左右子树
好的,我理解你的问题是让我写一个算法来交换二叉树中所有节点的左右子树。
以下是中文描述的算法:
1. 如果当前节点为空,则返回。
2. 否则,交换当前节点的左右子树。
3. 对当前节点的左子树调用递归函数,完成子树中所有节点的左右子树交换。
4. 对当前节点的右子树调用递归函数,完成子树中所有节点的左右子树交换。
下面是对应的 Python 代码:
```python
def invertTree(root):
if not root:
return
root.left, root.right = root.right, root.left
invertTree(root.left)
invertTree(root.right)
return root
```
希望这可以帮助到你!
编写算法,交换二叉树中所有结点的左右子树。
好的,以下是交换二叉树中所有节点的左右子树的算法:
```
1. 定义一个函数,名称为 swapTree。这个函数接受一个二叉树的根节点作为参数。
2. 如果根节点为空,那么直接返回。
3. 如果根节点不为空,那么交换它的左右子树。
4. 递归地调用 swapTree 函数,分别以原左子树和原右子树为参数,继续交换它们的左右子树。
5. 最后返回交换后的根节点。
```
下面是实现上述算法的 Python 代码:
```python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def swapTree(root):
if root is not None:
temp = root.left
root.left = root.right
root.right = temp
swapTree(root.left)
swapTree(root.right)
return root
```
注意,这个算法的时间复杂度为 O(n),其中 n 是二叉树中的节点数。
阅读全文
相关推荐












