题目:请完成一个函数,输入一颗二叉树,该函数输出它的镜像。二叉树节点定义如下:
class BinaryTreeNode{
double value;
BinaryTreeNode left;
BinaryTreeNode right;
public BinaryTreeNode(int value){
this.value = value;
}
}
思路:前序遍历二叉树,如果有子节点,则交换
解决方案:
public class Question27 {
static class BinaryTreeNode{
double value;
BinaryTreeNode left;
BinaryTreeNode right;
public BinaryTreeNode(int value){
this.value = value;
}
}
public static void mirrorRecursively(BinaryTreeNode node){
if (node == null) return;
if (node.left == null && node.right == null) return;
BinaryTreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
if (node.left != null){
mirrorRecursively(node.left);
}
if (node.right != null){
mirrorRecursively(node.right);
}
}
public static void main(String[] args) {
BinaryTreeNode pHead = new BinaryTreeNode(1);
BinaryTreeNode pAhead = new BinaryTreeNode(3);
BinaryTreeNode pBhead = new BinaryTreeNode(5);
BinaryTreeNode pChead = new BinaryTreeNode(7);
pHead.left = pAhead;
pHead.right = pBhead;
pBhead.left = pChead;
mirrorRecursively(pHead);
System.out.println(pHead.left.value);
}
}