27、二叉树的镜像
2018-04-03 16:27
190 查看
1、递归的方法
将根节点的左右子树对调,再将左右子树的左右子树对调,依次递归/** 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) return; TreeNode temp = root.left; root.left = root.right; root.right = temp; Mirror(root.left); Mirror(root.right); } }
2、循环的方法
import java.util.ArrayDeque; /** 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 ) return; ArrayDeque<TreeNode> stack = new ArrayDeque<TreeNode>(); //将根节点压入栈 stack.push(root); while(!stack.isEmpty()) { //弹出top节点并交换该结点的左右子树 TreeNode father = stack.pop(); TreeNode temp = father.left; father.left = father.right; father.right = temp; //左子树不为空则压入栈 if(father.left!=null) stack.push(father.left); //右子树不为空则压入栈 if(father.right!=null) stack.push(father.right); } } }
相关文章推荐
- OK 面试题27:二叉树的镜像
- 【剑指**】27.二叉树的镜像
- 剑指offer面试题27:二叉树的镜像
- 剑指Offer面试题27:二叉树的镜像
- 【剑指offer】面试题27:二叉树的镜像
- 【剑指offer】面试题 27:二叉树的镜像
- 剑指Offer(27)二叉树的镜像
- 剑指offer--面试题27:二叉树的镜像
- 剑指Offer 面试题27:二叉树的镜像 Java代码实现
- 二叉树镜像
- 剑指-二叉树镜像
- 二叉树的镜像
- 题目1521:二叉树的镜像
- 二叉树的镜像问题
- 码农小汪-剑指Offer之16-二叉树的镜像
- 剑指offer--二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- PHP获取二叉树镜像的方法
- 剑指Offer面试题:18.二叉树的镜像