剑指offer:面试题19、二叉树的镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:
源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
代码示例
public class Offer19 {
public static void main(String[] args) {
//构建树
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
//测试二叉树的镜像,使用先序遍历打印验证
Offer19 testObj = new Offer19();
testObj.preOrder(root);
System.out.println();
testObj.mirror(root);
testObj.preOrder(root);
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
//将二叉树进行镜像
public void mirror(TreeNode root) {
if (root == null)
return;
swap(root);
mirror(root.left);
mirror(root.right);
}
//交换当前节点的左右子树
private void swap(TreeNode root) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
//二叉树先序遍历
private void preOrder(TreeNode root) {
if (root == null)
return;
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
}