解法一:递归

将源节点的左孩子作为新节点的右孩子,右孩子作为新节点的左孩子,递归完成。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public TreeNode mirrorTree(TreeNode root) {
  12. if (root == null) {
  13. return null;
  14. }
  15. TreeNode mirrorNode = new TreeNode(root.val);
  16. if (root.left != null) {
  17. mirrorNode.right = mirrorTree(root.left);
  18. }
  19. if (root.right != null) {
  20. mirrorNode.left = mirrorTree(root.right);
  21. }
  22. return mirrorNode;
  23. }
  24. }