思路一:递归
1、求左子树镜像
2、求右子树镜像
3、求自身镜像
public class Solution {
/**
*1、先求左子树的镜像
*2、求右子树的镜像
*3、求自身的镜像
**/
public void Mirror(TreeNode root) {
if(root==null){
return;
}
Mirror(root.left);
Mirror(root.right);
if(root.left!=null||root.right!=null){
TreeNode temp = root.left;
root.left=root.right;
root.right=temp;
}
return;
}
}思路二:广度优先遍历
public class Solution {
//广度优先遍历bfs
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);
}
}
}
}
京公网安备 11010502036488号