題目:請(qǐng)完成一個(gè)函數(shù)务荆,輸入一個(gè)二叉樹,該函數(shù)輸出它的鏡像剪菱。
代碼如下:
package demo;
public class Test19 {
public static class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
public static void mirrorRecursively(BinaryTreeNode node) {
if(node != null) {
// 交換結(jié)點(diǎn)左右2個(gè)子樹
BinaryTreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
// 對(duì)結(jié)點(diǎn)的左右子樹再進(jìn)行處理
mirrorRecursively(node.left);
mirrorRecursively(node.right);
}
}
/**
* 中序遍歷二叉樹
* @param node
*/
public static void printTree(BinaryTreeNode node) {
if(node != null) {
printTree(node.left);
printTree(node.right);
System.out.print(node.value + " ");
}
}
測(cè)試代碼1:
public static void main(String[] args) {
/**
* 1. 普通二叉樹
*/
BinaryTreeNode node = new BinaryTreeNode();
node.value = 8;
node.left = new BinaryTreeNode();
node.left.value = 6;
node.right = new BinaryTreeNode();
node.right.value = 10;
node.left.left = new BinaryTreeNode();
node.left.left.value = 5;
node.left.right = new BinaryTreeNode();
node.left.right.value = 7;
node.right.left = new BinaryTreeNode();
node.right.left.value = 9;
node.right.right = new BinaryTreeNode();
node.right.right.value = 11;
System.out.println("普通二叉樹是:");
printTree(node);
System.out.println();
System.out.println("普通二叉樹的鏡像是:");
mirrorRecursively(node);
printTree(node);
}
測(cè)試代碼2:
public static void main(String[] args) {
/**
* 2. 所有結(jié)點(diǎn)都沒有右子樹的二叉樹
*/
BinaryTreeNode node2 = new BinaryTreeNode();
node2.value = 1;
node2.left = new BinaryTreeNode();
node2.left.value = 3;
node2.left.left = new BinaryTreeNode();
node2.left.left.value = 5;
node2.left.left.left = new BinaryTreeNode();
node2.left.left.left.value = 7;
node2.left.left.left.left = new BinaryTreeNode();
node2.left.left.left.left.value = 9;
System.out.println("所有結(jié)點(diǎn)都沒有右子樹的二叉樹是:");
printTree(node2);
System.out.println();
System.out.println("該二叉樹的鏡像是:");
mirrorRecursively(node2);
printTree(node2);
}
測(cè)試代碼3:
public static void main(String[] args) {
/**
* 3. 所有結(jié)點(diǎn)都沒有左子樹的二叉樹
*/
BinaryTreeNode node3 = new BinaryTreeNode();
node3.value = 0;
node3.right = new BinaryTreeNode();
node3.right.value = 2;
node3.right.right = new BinaryTreeNode();
node3.right.right.value = 4;
node3.right.right.right = new BinaryTreeNode();
node3.right.right.right.value = 6;
node3.right.right.right.right = new BinaryTreeNode();
node3.right.right.right.right.value = 8;
System.out.println("所有結(jié)點(diǎn)都沒有左子樹的二叉樹是:");
printTree(node3);
System.out.println();
System.out.println("該二叉樹的鏡像是:");
mirrorRecursively(node3);
printTree(node3);
}