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;
        }
  • 相关阅读:
    使用T4为数据库自动生成实体类
    asp.net 下OnClientClick的妙用
    使用缓存的9大误区(上)
    使用缓存的9大误区(下)
    毕业后的五年拉开大家差距的原因在哪里
    mysql字符集
    redhat网络基础配置
    mysql远程连接问题
    Hibernate hql语句修改部分字段
    JQuery使用方法总结
  • 原文地址:https://www.cnblogs.com/lfdingye/p/7365999.html
Copyright © 2011-2022 走看看