zoukankan      html  css  js  c++  java
  • 求一棵二叉树的镜像

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

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

    递归:破坏原有的二叉树

      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;
        }
  • 相关阅读:
    mybatis-plus
    AOP中Cache操作实现
    ab和webbench的安装以及使用
    git commit的提交规范
    CGI、FastCGI、PHP-CGI与PHP-FPM的概念以及各个之间的关系
    PHP垃圾回收机制(GC)
    PhpStorm中php文件如何在console中运行
    ELK-logstash导入数据以及配合kibana使用
    领扣刷题——关于数
    Uncaught SyntaxError: Illegal return statement
  • 原文地址:https://www.cnblogs.com/lfdingye/p/7365999.html
Copyright © 2011-2022 走看看