博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
求一棵二叉树的镜像
阅读量:6945 次
发布时间:2019-06-27

本文共 2184 字,大约阅读时间需要 7 分钟。

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

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

递归:破坏原有的二叉树

  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
stack = new Stack
(); 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
stack = new Stack
(); Stack
newStack = new Stack
(); 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

你可能感兴趣的文章
家庭里如何搭建一个互联网可访问的服务器
查看>>
eclipse与SVN 结合(删除SVN中已经上传的问题)
查看>>
深入理解Fsync
查看>>
去掉xcode编译warning:ld: warning: directory not found for option '-L
查看>>
杭电1702--ACboy needs your help again!
查看>>
web前端开发分享-css,js进阶篇
查看>>
安大校赛/异或运算一题。
查看>>
强制回收和IDisposable.Dispose方法
查看>>
mybatis plus条件构造器
查看>>
quick sort(重复数版)
查看>>
乌班图 root权限获取
查看>>
Java内部类
查看>>
趣说Java:我是一个线程
查看>>
HDU 1498 50 years, 50 colors
查看>>
杭电 1874 畅通工程续 (求某节点到某节点的最短路径)
查看>>
PHP添加mongodb驱动的问题
查看>>
JS将秒转换为 天-时-分-秒
查看>>
CRUD
查看>>
Unity3D性能优化--- 收集整理的一堆
查看>>
数据库基础
查看>>