/*
* 操作给定的二叉树,将其变换为源二叉树的镜像
* 二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
思路:画图,把每个转化的过程都画下来
*/
public class BinaryTreeMirror {
public void Mirror(TreeNode root) {
if(root == null || (root.left == null && root.right == null)) {
return;
}
//交换根节点左右节点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
public static void main(String[] args) {
TreeNode root1 = new TreeNode(8);
root1.left = new TreeNode(6);
root1.right = new TreeNode(10);
new BinaryTreeMirror().Mirror(root1);
System.out.println(root1.val + " " + root1.left.val + " " + root1.right.val);
}
}
《剑指offer》-二叉树的镜像
最新推荐文章于 2021-12-07 15:40:19 发布