题目
思路
递归的思想
结束条件是空
树的镜像就是左子树的镜像放在右子树
右子树的镜像放在左子树
思路二:
实际上经过几个例子之后我们可以发现只需要让每个节点都交换左右就可以了,所以我们遍历所有节点交换左右
代码
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return TreeNode类
*/
public TreeNode Mirror (TreeNode pRoot) {
// write code here
if(pRoot==null)return null;
TreeNode temp=pRoot.left;
pRoot.left=Mirror(pRoot.right);
pRoot.right=Mirror(temp);
return pRoot;
}
}
方法二:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return TreeNode类
*/
public TreeNode Mirror (TreeNode pRoot) {
// write code here
//广度优先搜索
if(pRoot==null)return null;
LinkedList<TreeNode> l=new LinkedList<>();
l.addLast(pRoot);
while(!l.isEmpty()){
TreeNode cur=l.removeFirst();
if(cur!=null){
//这里是确保null也可以进入队列进行交换,但是null不需要交换和入队自己的孩子节点
l.addLast(cur.left);
l.addLast(cur.right);
TreeNode temp;
temp=cur.left;
cur.left=cur.right;
cur.right=temp;
}
//
}
return pRoot;
}
}