题目
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
分析
代码实现
class TreeNode{
int val
= 0;
TreeNode left
= null
;
TreeNode right
= null
;
public TreeNode(int val
) {
this.val
= val
;
}
}
public class Solution {
public static void main(String
[] args
) {
TreeNode root
= new TreeNode(4);
TreeNode node1
= new TreeNode(2);
TreeNode node2
= new TreeNode(7);
TreeNode node3
= new TreeNode(1);
TreeNode node4
= new TreeNode(3);
TreeNode node5
= new TreeNode(6);
TreeNode node6
= new TreeNode(9);
root
.left
= node1
;
root
.right
= node2
;
node1
.left
= node3
;
node1
.right
= node4
;
node2
.left
= node5
;
node2
.right
= node6
;
System
.out
.println();
Mirror(root
);
System
.out
.println();
}
public TreeNode
mirrorTree(TreeNode root
) {
if (root
== null
){
return null
;
}
root
.left
= mirrorTree(root
.right
);
root
.right
= mirrorTree(root
.left
);
return root
;
}
}
public class Solution {
public static void main(String
[] args
) {
TreeNode root
= new TreeNode(4);
TreeNode node1
= new TreeNode(2);
TreeNode node2
= new TreeNode(7);
TreeNode node3
= new TreeNode(1);
TreeNode node4
= new TreeNode(3);
TreeNode node5
= new TreeNode(6);
TreeNode node6
= new TreeNode(9);
root
.left
= node1
;
root
.right
= node2
;
node1
.left
= node3
;
node1
.right
= node4
;
node2
.left
= node5
;
node2
.right
= node6
;
System
.out
.println();
Mirror(root
);
System
.out
.println();
}
public static void Mirror(TreeNode root
) {
if (root
== null
) {
return;
}
TreeNode temp
;
if (root
.right
!= null
|| root
.left
!= null
) {
temp
= root
.left
;
root
.left
= root
.right
;
root
.right
= temp
;
}
Mirror(root
.left
);
Mirror(root
.right
);
}
}
转载请注明原文地址:https://tech.qufami.com/read-15524.html