程序运行截图:
import java.util.HashMap;
public class Algorithm1 {
/*
[二叉树的镜像]
[题目]
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:
源二叉树
8
| |
6 10
| | | |
5 7 9 11
镜像二叉树
8
| |
10 6
| | | |
11 9 7 5
*/
private static boolean printRoot = true;
public static void main(String[] args) {
TreeNode test = createTestTree();
printTree(test, false);
swapTreeNodeChild(test);
System.out.println("---------------------------");
printTree(test, false);
}
public static TreeNode createTestTree() {
TreeNode node5 = new TreeNode(2, 5, null, null);
TreeNode node7 = new TreeNode(2, 7, null, null);
TreeNode node9 = new TreeNode(2, 9, null, null);
TreeNode node11 = new TreeNode(2, 11, null, null);
TreeNode node6 = new TreeNode(1, 6, node5, node7);
TreeNode node10 = new TreeNode(1, 10, node9, node11);
TreeNode node8 = new TreeNode(0, 8, node6, node10);
return node8;
}
public static void swapTreeNodeChild(TreeNode node) {
if (node != null) {
TreeNode temp = node.leftNode;
node.leftNode = node.rightNode;
node.rightNode = temp;
swapTreeNodeChild(node.leftNode);
swapTreeNodeChild(node.rightNode);
}
}
public static void printTree(TreeNode node, boolean isLeftNode) {
HashMap<Integer, StringBuilder> map = new HashMap<>();
mapTreeNode(node, map);
for(Integer i : map.keySet()) {
System.out.println(map.get(i).toString()+"\n");
}
}
public static void mapTreeNode(TreeNode node, HashMap<Integer, StringBuilder> map) {
if (node != null) {
StringBuilder sb = map.get(node.depth);
if (sb == null)
sb = new StringBuilder();
sb.append(node.content+" ");
map.put(node.depth, sb);
mapTreeNode(node.leftNode, map);
mapTreeNode(node.rightNode, map);
}
}
}