题目及测试
package sword019;
/*题目描述:请完成一个函数,输入一个二叉树,该函数输出它的镜像;
*/
public class main {
public static void main(String[] args) {
Object[] x=new Object[]{4,1,6,0,2,5,null};
BinaryTree tree=new BinaryTree(x);
BinaryTree.printTree(tree.root);
test(tree.root);
}
private static void test(TreeNode ito) {
Solution solution = new Solution();
TreeNode rtn;
long begin = System.currentTimeMillis();
rtn = solution.mirroOfBinTree(ito);//执行程序
long end = System.currentTimeMillis();
System.out.println("rtn=" );
BinaryTree.printTree(rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功)
我们先先序遍历这个树的子结点,如果子结点有子结点,那么就交换,当交换完成所有的非叶子结点,那么就是我们所要求的镜像。
package sword019;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode mirroOfBinTree(TreeNode root) {
if(root == null) {
return null;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
mirroOfBinTree(root.left);
mirroOfBinTree(root.right);
return root;
}
}