題目描述
操作給定的二叉樹,將其變換爲源二叉樹的鏡像。
package tree;
import java.util.LinkedList;
import java.util.Queue;
//二叉樹鏡像
public class Mirror_18 {
//遞歸
public static void Mirror(TreeNode_18 root) {
if (root == null) {
return;
}
TreeNode_18 temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
//非遞歸方法,利用二叉樹的廣度優先搜索
//1. queue的增加元素方法add和offer的區別在於,
// add方法在隊列滿的情況下將選擇拋異常的方法來表示隊列已經滿了,
// 而offer方法通過返回false表示隊列已經滿了;在有限隊列的情況,使用offer方法優於add方法;
//2. remove方法和poll方法都是刪除隊列的頭元素,remove方法在隊列爲空的情況下將拋異常,
// 而poll方法將返回null;
public static void Mirror1(TreeNode_18 root) {
if(root == null) return;
//隊列存的是TreeNode
Queue<TreeNode_18> nodes = new LinkedList<>();
TreeNode_18 curr, temp;
nodes.offer(root);
while(!nodes.isEmpty()){
int len = nodes.size();
for(int i = 0; i < len; i++){
curr = nodes.poll();
temp = curr.left;
curr.left = curr.right;
curr.right = temp;
if(curr.left != null) nodes.offer(curr.left);
if(curr.right != null) nodes.offer(curr.right);
}
}
}
public static void main(String[] args) {
TreeNode_18 root = new TreeNode_18(8);
root.left = new TreeNode_18(6);
root.right = new TreeNode_18(10);
root.left.left = new TreeNode_18(5);
root.left.right = new TreeNode_18(7);
root.right.left = new TreeNode_18(9);
root.right.right = new TreeNode_18(11);
Mirror1(root);
System.out.println(root);
}
}