剑指Offer:面试题19——二叉树的镜像(java实现)

问题描述:

操作给定的二叉树,将其变换为源二叉树的镜像。 二叉树结点定义为:

public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null; public TreeNode(int val) {
this.val = val; } }

例如:

        8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5

思路:

从根结点出发,递归的,首先交换左右子树,然后将变化后的左右子树变换为其镜像。

代码:

public void Mirror(TreeNode root) {

        if(root == null){
return;
} if(root.left == null && root.right == null){
return;
} TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp; if(root.left != null){//这里加入判空条件可以及时终止递归,会少进行一次递归,减少栈存储的压力
Mirror(root.left);
}
if(root.right != null){
Mirror(root.right);
}
}
上一篇:WEB 安全之 SQL注入<一> 盲注


下一篇:Web安全之SQL注入(原理,绕过,防御)