操作给定的二叉树,将其变换为源二叉树的镜像。
题目链接:https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
// 递归方式
public void Mirror(TreeNode root) {
if(root!=null){
if(root.left!=null || root.right!=null){
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
Mirror(root.left);
Mirror(root.right);
}
}
}
// 循环方式
public void Mirror(TreeNode root) {
if(root!=null){
java.util.Queue<TreeNode> queue = new java.util.LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode tmp = queue.poll();
TreeNode left = tmp.left;
tmp.left = tmp.right;
tmp.right = left;
if(tmp.left!=null) queue.add(tmp.left);
if(tmp.right!=null) queue.add(tmp.right);
}
}
}
网友评论