剑指offer题17

来源:互联网 发布:ajax json 提交 编辑:程序博客网 时间:2024/06/15 03:56
package jianzhioffer;import java.util.LinkedList;import java.util.Queue;import java.util.Scanner;import jianzhioffer.BinaryTree;/** * 操作给定的二叉树,将其变换为源二叉树的镜像。 * 二叉树的镜像定义:源二叉树         8       /  \      6   10     / \  / \    5  7 9 11    镜像二叉树        8       /  \      10   6     / \  / \    11 9 7  5 * *///树节点类/* class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/public class Solution17 {//递归调换左右子树/*public static void Mirror(TreeNode root) {        if(root == null) return;        if(root.left == null && root.right ==null) return;        TreeNode node1 = root.left;        TreeNode node2 = root.right;        root.left = node2;        root.right = node1;        Mirror(root.left);        Mirror(root.right);        }*///非递归版,借助队列实现public static void Mirror(TreeNode root) {if(root == null) return;Queue<TreeNode> queue = new LinkedList<TreeNode>();queue.add(root);TreeNode node;while(!queue.isEmpty()){node = queue.poll();if(node == null) continue;TreeNode node1 = node.left;TreeNode node2 = node.right;node.left = node2;node.right = node1;queue.add(node2);queue.add(node1);}}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int[] a1 = new int[n];for(int i = 0;i<n;i++){a1[i] = sc.nextInt();}TreeNode tree1 = new TreeNode(a1[0]);TreeNode tree2 = new TreeNode(a1[1]);TreeNode tree3 = new TreeNode(a1[2]);TreeNode tree4 = new TreeNode(a1[3]);TreeNode tree5 = new TreeNode(a1[4]);TreeNode tree6 = new TreeNode(a1[5]);TreeNode tree7 = new TreeNode(a1[6]);tree1.left = tree2;    tree1.right = tree3;    tree2.left = tree4;    tree2.right = tree5;    tree3.left = tree6;    tree3.right = tree7;        BinaryTree bt = new BinaryTree();    System.out.println("源二叉树的前序遍历结果:");    bt.preOrder(tree1);        System.out.println("镜像二叉树的前序遍历结果:");    Mirror(tree1);    bt.preOrder(tree1);}}

原创粉丝点击