package 剑指Offer.二叉树.二叉树镜像; import java.util.ArrayDeque; import java.util.LinkedList; import java.util.Queue; /** * @program:多线程和IO * @descripton:输入一个二叉树,利用一个函数输出其镜像 * @author:ZhengCheng * @create:2021/10/19-18:54 **/ public class MirrorTree { public static void main(String[] args) throws Exception{ //创建一颗二叉树,我们可以用层次遍历来验证我们的想法 //init Node node4 = new Node("4"); Node node2 = new Node("2"); Node node7 = new Node("7"); Node node1 = new Node("1"); Node node3 = new Node("3"); Node node6 = new Node("6"); // Node node9 = new Node("9"); node4.left = node2; node4.right = node7; node2.left = node1; node2.right = node3; // node7.right = node9; node7.left = node6; MirrorTree m = new MirrorTree(); m.stepOut(node4); m.mirrorTree2(node4); m.stepOut(node4); } private void mirrorTree1 (Node head){ //递归,没想出来。 } private void mirrorTree2 (Node head){ //使用栈的方法。类比层次遍历 On On LinkedList<Node> list = new LinkedList<>(); Node temp = head; list.add(temp); while (!list.isEmpty()){ Node poll = list.poll(); if (poll.left != null){ list.add(poll.left); } if (poll.right != null){ list.add(poll.right); } //交换 Node swap = poll.left; poll.left = poll.right; poll.right = swap; } } //correct private void stepOut (Node head)throws Exception{ Node temp = head; Queue<Node> q = new LinkedList<>(); q.add(temp); while (!q.isEmpty()){ Node poll = q.poll(); System.out.print(poll); if (poll.left != null ){ q.add(poll.left); //消除nullpointerException }else if (!poll.getId().equals("null")&& (poll.left!=null || poll.right != null)){ q.add(new Node("null")); } if (poll.right != null){ q.add(poll.right); }else if (!poll.getId().equals("null") && (poll.left!=null || poll.right != null)){ q.add(new Node("null")); } } System.out.println(); } } class Node { public Node left ; public Node right ; private String id; @Override public String toString() { return "" + id +"-"; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Node(String id) { this.id = id; } }