JZ18:操作给定的二叉树,将其变换为源二叉树的镜像
解析:同JZ38,二叉树分析一遍分两组方法:递归方法;非递归方法
代码:
方法1:递归方法
public void Mirror(TreeNode root){
if(root == null)
return;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
方法2:非递归方法
public void Mirror(TreeNode root){
if(root == null)
return;
Queue<TreeNode> nodes = new LinkedList<>();
TreeNode 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);
}
}
}