问题
给定一个二叉树,你需要把它转换成它的镜像。这个问题也被称为倒置二叉树问题。
例子
处理方法
我们可以用DFS来解决这个问题。考虑一种情况,当你需要将下面的二叉树转换成镜像树时。
1
/ \
2 3
我们将简单地交换根的左右两个子树。这种算法也可以在子树上扩展。我们以任何顺序遍历一棵树,并不断交换每个节点的左右子女。最终,这将导致给定树的镜像。大多数树的问题都是通过扩展算法来解决的,就像我们在这里做的那样。
复杂度分析
时间复杂度为O(N),空间复杂度在最坏的情况下也为O(N)。
C++编程
#include <iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left, *right;
TreeNode(int val)
{
this->val = val;
this->left = this->right = nullptr;
}
};
void printTree(TreeNode* root)
{
if (root == nullptr) {
return;
}
cout << root->val << " ";
printTree(root->left);
printTree(root->right);
}
bool dfs(TreeNode* root)
{
if (!root) {
return true;
}
输出
1 3 2
Java编程
class TreeNode
{
int val;
TreeNode left = null, right = null;
TreeNode(int val) {
this.val = val;
}
}
class Main
{
public static void printTree(TreeNode root)
{
if (root == null) {
return;
}
System.out.print(root.val + " ");
printTree(root.left);
printTree(root.right);
}
public static void swap(TreeNode root)
{
if (root == null) {
return;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
public static void dfs(TreeNode root)
{
if (root == null) {
return;
}
输出
1 3 2
Python编程
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def printTree(root):
if root is None:
return
print(root.val, end=' ')
printTree(root.left)
printTree(root.right)
def swap(root):
if root is None:
return
temp = root.left
root.left = root.right
root.right = temp
def dfs(root):
if root is None:
return
# convert left subtree
dfs(root.left)
# convert right subtree
dfs(root.right)
# swap left subtree with right subtree
swap(root)
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
dfs(root)
printTree(root)
輸出
1 3 2