Solution 15: 树的镜像
问题描述
输入一颗BST,将该树转换为它的镜像。
要求使用递归和非递归两种思路解决。
解决思路
非递归基于BST。
程序
public class MirrorOfBST { public void toMirrorRec(TreeNode root) { if (root == null) { return ; } TreeNode left = root.left; TreeNode right = root.right; root.left = right; root.right = left; toMirrorRec(left); toMirrorRec(right); } public void toMirrorNoRec(TreeNode root) { if (root == null) { return ; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node != null) { TreeNode left = node.left; TreeNode right = node.right; node.left = right; node.right = left; queue.offer(right); queue.offer(left); } } } }