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;
        }
  • 相关阅读:
    define vs const vs enum
    解决Ubuntu 14.04 LTS 浏览网页速度慢的问题
    C语言两种产生矩阵的方法
    GTK 添加图标
    Unix Socket 端口 reuse
    Linux GTK Hello,World
    插件使用记录
    原型链和new
    each函数循环数据表示列举,列举循环的时候添加dom的方法
    字体圆润属性的使用-webkit-font-smoothing: antialiased
  • 原文地址:https://www.cnblogs.com/lfdingye/p/7365999.html
Copyright © 2011-2022 走看看