求一棵二叉树的镜像

题目:求一棵二叉树的镜像

思路:破坏原有的二叉树   不破坏原有二叉树,新建一个新的二叉树

递归:破坏原有的二叉树

  public static TreeNode mirror(TreeNode root){
        if(root == null)
            return null;
        TreeNode left = mirror(root.left);
        TreeNode right = mirror(root.right);
        root.left = right;
        root.right = left;
        return root;  //每次返回到上一个节点
    }

递归:不破坏原有的二叉树

public static TreeNode newMirror(TreeNode root){
        if(root == null)
            return null;
        TreeNode node = new TreeNode(root.val);
        node.left = newMirror(root.right);
        node.right = newMirror(root.left);
        return node;
    }

 迭代:破坏原来的二叉树

public static void mirrorDestroy(TreeNode root){
        if(root == null)
            return;
          Stack<TreeNode> stack = new Stack<TreeNode>();
          stack.push(root);
          while(!stack.isEmpty()){
              TreeNode cur = stack.pop();
              
              TreeNode tmp  = cur.right;
              cur.right = cur.left;
              cur.left = tmp;
              
              if(cur.left != null){
                  stack.push(cur.left);
              }
              if(cur.right != null){
                  stack.push(cur.right);
              }
          }
    }

迭代:不破坏原来的二叉树

public static TreeNode mirrorUndestory(TreeNode root){
        if(root == null)
            return null;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        Stack<TreeNode> newStack = new Stack<TreeNode>();
        stack.push(root);
        
        TreeNode newRoot = new TreeNode(root.val);
        newStack.push(newRoot);
        
        while(!stack.isEmpty()){
            TreeNode cur = stack.pop();
            TreeNode newCur = newStack.pop();
            
            if(cur.right != null){
                stack.push(cur.right);
                newCur.left = new TreeNode(cur.right.val);
                newStack.push(newCur.left);
            }
            if(cur.left != null){
                stack.push(cur.left);
                newCur.right = new TreeNode(cur.left.val);
                newStack.push(newCur.right);
            }
        }
        return newRoot;
    }
原文地址:https://www.cnblogs.com/lfdingye/p/7365999.html