操作给定的二叉树,将其变换为源二叉树的镜像。
代码
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
/**
* 递归方式对树做镜像处理</br>
* x | x </br>
* y z | z y </br>
* @param root
*/
public static void mirror(TreeNode root) {
// 如果跟节点为空,无需处理
if (root == null) {
return;
}
// 左子节点和右子节点都为空,无需处理
if (root.left == null && root.right == null) {
return;
}
// 左子节点不为空,则对该子节点做镜像处理
if (root.left != null) {
mirror(root.left);
}
// 右子节点不为空,则对该子节点做镜像处理
if (root.right != null) {
mirror(root.right);
}
// 交换当前节点的左右子节点位置
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
/**
* 使用栈的方式对树做镜像处理</br>
* x | x </br>
* y z | z y </br>
* @param root
*/
public static void mirrorByStack(TreeNode root) {
// 如果跟节点为空,无需处理
if (root == null) {
return;
}
// 左子节点和右子节点都为空,无需处理
if (root.left == null && root.right == null) {
return;
}
// 存放需要交换子节点的节点,节点不为null时放入栈中,如果为null,不需要处理所以无需放入stack中
// 比如当前的树是
// 5
// 3 18
// 2 4
//一开始根节点5就被放入了栈,但是第一次就取出来了,并交换了其子节点,此时是
// 5
// 18 3
// 2 4
// 此时将18和3放入stack中,下一次去栈中取出的是3,因为栈是后入先出的,交换其子节点,此时是
// 5
// 18 3
// 4 2
// 此时将4和2放入stack中,此时栈中的元素时2,4,18,以此取出即可,因为该三个节点都没有子节点
Stack<TreeNode> stack = new Stack<>();
// 首先将根节点放入栈中
stack.push(root);
// 一直到栈中没有需要交换左右子节点的节点
while (stack.size() > 0) {
// 从栈中取出栈顶元素,即需要被交换左右子节点的节点
TreeNode node = stack.pop();
// 当前节点任一子节点不为null,则交其左右子节点位置
if (node.left != null || node.right != null) {
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
// 左子节点不为空,则push到栈中,等待之后的处理
if (node.left != null) {
stack.push(node.left);
}
// 右子节点不为空,则push到栈中,等待之后的处理
if (node.right != null) {
stack.push(node.right);
}
}
}
/**
* 前序遍历打印树
* @param root
*/
private static void printTree(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
printTree(root.left);
printTree(root.right);
}
public static void main(String[] args) {
TreeNode root = buildTree1();
printTree(root);
mirrorByStack(root);
System.out.println();
printTree(root);
}
/**
* 创建tree1:</br>
* 5</br>
* 3 18</br>
* 2 4</br>
* @return
*/
private static TreeNode buildTree1(){
TreeNode root = new TreeNode(5);
TreeNode left = new TreeNode(3);
TreeNode left1 = new TreeNode(2);
TreeNode right1 = new TreeNode(4);
left.left = left1;
left.right = right1;
TreeNode right = new TreeNode(18);
root.left = left;
root.right = right;
return root;
}