操作给定的二叉树,将其变换为源二叉树的镜像,如下图所示。
输入:
{8,6,10,5,7,9,11}
返回值:
{8,10,6,11,9,7,5}
第一种解决办法,循环遍历左右两个节点,然后交换即可,采用递归方法解决,代码如下。
public static TreeNode firstMirror (TreeNode pRoot) {
if(null == pRoot){
return null;
}
if(null == pRoot.left && null == pRoot.right){
return pRoot;
}
TreeNode tem = pRoot.left;
pRoot.left = pRoot.right;
pRoot.right = tem;
firstMirror(pRoot.left);
firstMirror(pRoot.right);
return pRoot;
}
第二种解决方法,如果当前节点为 null,返回 null ,否则先分别对该节点的左右孩子进行镜像处理,然后将该节点的左指针指向右孩子,右指针指向左孩子,对该节点进行镜像处理,代码如下。
public static TreeNode secondMirror (TreeNode pRoot) {
if(null == pRoot){
return null;
}
if(null == pRoot.left && null == pRoot.right){
return pRoot;
}
TreeNode right = secondMirror(pRoot.right);
TreeNode left = secondMirror(pRoot.left);
pRoot.right = left;
pRoot.left = right;
return pRoot;
}
第三种方法,采用先序遍历的方式,如果根节点不为空,则入栈,当栈不为空的时候,出栈,而且交换左右节点,如果左右节点不为空,则入栈,循环刚才的操作,代码如下。
public static TreeNode thirdMirror (TreeNode pRoot) {
if(null == pRoot){
return null;
}
if(null == pRoot.left && null == pRoot.right){
return pRoot;
}
Stack<TreeNode> treeNodes = new Stack<>();
treeNodes.push(pRoot);
while (!treeNodes.empty()){
TreeNode pop = treeNodes.pop();
if(null != pop.left || null != pop.right){
TreeNode tem = pop.right;
pop.right = pop.left;
pop.left = tem;
}
if(null != pop.left){
treeNodes.push(pop.left);
}
if(null != pop.right){
treeNodes.push(pop.right);
}
}
return pRoot;
}
完整代码如下
public class MainMirror {
public static void main(String[] args) {
TreeNode a1 = new TreeNode(1);
TreeNode a2 = new TreeNode(7);
TreeNode a3 = new TreeNode(3);
TreeNode a4 = new TreeNode(2);
TreeNode a5 = new TreeNode(6);
TreeNode a6 = new TreeNode(4);
TreeNode a7 = new TreeNode(5);
a1.left = a2;
a1.right = a3;
a2.left = a4;
a2.right = a5;
a4.left = a6;
a4.right = a7;
TreeNode mirror = thirdMirror(a1);
System.out.println("mirror = " + mirror);
}
public static TreeNode firstMirror (TreeNode pRoot) {
if(null == pRoot){
return null;
}
if(null == pRoot.left && null == pRoot.right){
return pRoot;
}
TreeNode tem = pRoot.left;
pRoot.left = pRoot.right;
pRoot.right = tem;
firstMirror(pRoot.left);
firstMirror(pRoot.right);
return pRoot;
}
public static TreeNode secondMirror (TreeNode pRoot) {
if(null == pRoot){
return null;
}
if(null == pRoot.left && null == pRoot.right){
return pRoot;
}
TreeNode right = secondMirror(pRoot.right);
TreeNode left = secondMirror(pRoot.left);
pRoot.right = left;
pRoot.left = right;
return pRoot;
}
public static TreeNode thirdMirror (TreeNode pRoot) {
if(null == pRoot){
return null;
}
if(null == pRoot.left && null == pRoot.right){
return pRoot;
}
Stack<TreeNode> treeNodes = new Stack<>();
treeNodes.push(pRoot);
while (!treeNodes.empty()){
TreeNode pop = treeNodes.pop();
if(null != pop.left || null != pop.right){
TreeNode tem = pop.right;
pop.right = pop.left;
pop.left = tem;
}
if(null != pop.left){
treeNodes.push(pop.left);
}
if(null != pop.right){
treeNodes.push(pop.right);
}
}
return pRoot;
}
}