剑指offer No.19 二叉树的镜像 java实现(递归+非递归)
2019-03-15 21:29
302 查看
操作给定的二叉树,将其变换为源二叉树的镜像。
[code]二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5
非递归 栈实现
[code]/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.*; public class Solution { public void Mirror(TreeNode root) { if(root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.empty()) { TreeNode node = stack.pop(); if(node.left != null || node.right != null) { TreeNode temp = node.left; node.left = node.right; node.right = temp; } if(node.left != null) stack.push(node.left); if(node.right != null) stack.push(node.right); } } }
递归
[code]/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public void Mirror(TreeNode root) { if(root == null||(root.left == null && root.right == null)) return; TreeNode pTemp = root.left; root.left = root.right; root.right = pTemp; if(root.left != null) Mirror(root.left); if(root.right != null) Mirror(root.right); } }
相关文章推荐
- 【剑指offer——JAVA实现】二叉树的镜像
- 剑指offer---二叉树的镜像---java实现
- 剑指Offer:面试题6——重建二叉树(java实现)
- 剑指Offer:面试题25——二叉树中和为某一值的路径(java实现)
- 剑指offer----二叉树的深度----java实现
- 剑指offer----把二叉树打印成多行----java实现
- 剑指offer面试题61 按之字形顺序打印二叉树(java实现)
- 剑指offer第十八题【二叉树的镜像】c++实现
- 二叉树的镜像[剑指offer]之python实现
- 剑指Offer面试题18树的子结构(递归),面试题19二叉树的镜像(递归和非递归用栈)
- 剑指offer-重建二叉树 java实现
- <剑指offer 面试题7-1>构建二叉树以及实现遍历 Java
- 剑指offer 重建二叉树 java实现
- 剑指Offer面试题19(Java版):二叉树的镜像
- 剑指offer阅读笔记 之面试题19 实现二叉树的镜像 之 又复习一遍二叉树
- 【剑指offer-Java版】19二叉树的镜像
- 剑指offer----从上到下打印二叉树----java实现
- 剑指Offer面试题61:按之子型打印二叉树 Java实现
- 剑指Offer面试题6:重建二叉树 Java实现
- 剑指Offer面试题60:把二叉树打印成多行 Java实现