题目描述
输入描述:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5
其实就是交换二叉树的左右子树,可用递归实现:
交换根节点的左右子树,再分别对左子树进行镜像和右子树进行镜像
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class jingzi {
public void Mirror(TreeNode root) {
if(root == null){
return;
}else{
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
Mirror(root.left);
Mirror(root.right);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(4);
root.left = new TreeNode(5);
root.right = new TreeNode(6);
jingzi jj = new jingzi();
jj.Mirror(root);
}
}