1.题目:
操作给定的二叉树,将其变换为源二叉树的镜像。
比如: 源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 52.思路:
方法一:递归
1 .终止条件: 当节点root为空时(即越过叶节点),则返回null ;
2. 递推工作:
初始化节点tmp,用于暂存root的左子节点;
开启递归 右子节点 mirrorTree(root.right),并将返回值作为root的左子节点 。
开启递归 左子节点 mirrorTree(tmp),并将返回值作为root的右子节点 。时间复杂度 O(N): 其中 N为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N) 时间。
空间复杂度 O(N): 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)大小的栈空间。
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;
Stack<TreeNode> s=new Stack<>();
s.push(pRoot);//初始化
while(!s.isEmpty()){
//交换
TreeNode node=s.pop();
TreeNode temp=node.left;
node.left=node.right;
node.right=temp;
//入栈
if(node.left!=null) s.push(node.left);
if(node.right!=null) s.push(node.right);
}
return pRoot;
}
}
京公网安备 11010502036488号