难度系数 ⭐⭐难在思路
时间限制 C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
题目内容 操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
思路 二叉树的镜像,其实就是把二叉树每个节点的左右孩子换一下,所以一边遍历一边换就可以了。
package nowcoder;
import java.util.LinkedList;
import java.util.Queue;
public class No21 {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
public static void Mirror(Node head){
if (head == null) return;
Queue<Node> queue = new LinkedList<>();
queue.offer(head);
while (!queue.isEmpty()){
Node flag = queue.poll();
if (flag.left != null) queue.offer(flag.left);
if (flag.right != null) queue.offer(flag.right);
Node f = flag.left;
flag.left = flag.right;
flag.right = f;
}
}
public static void printTree(Node head) {
System.out.println("Binary Tree:");
printInOrder(head, 0, "H", 17);
System.out.println();
}
public static void printInOrder(Node head, int height, String to, int len) {
if (head == null) {
return;
}
printInOrder(head.right, height + 1, "v", len);
String val = to + head.value + to;
int lenM = val.length();
int lenL = (len - lenM) / 2;
int lenR = len - lenM - lenL;
val = getSpace(lenL) + val + getSpace(lenR);
System.out.println(getSpace(height * len) + val);
printInOrder(head.left, height + 1, "^", len);
}
public static String getSpace(int num) {
String space = " ";
StringBuffer buf = new StringBuffer("");
for (int i = 0; i < num; i++) {
buf.append(space);
}
return buf.toString();
}
public static void main(String[] args){
Node head = new Node(8);
head.left = new Node(6);
head.right = new Node(10);
head.left.left = new Node(5);
head.left.right = new Node(7);
head.right.left = new Node(9);
head.right.right = new Node(11);
printTree(head);
Mirror(head);
printTree(head);
}
}