二叉树的镜像

本文介绍了一种通过递归方式实现二叉树镜像的方法。通过对二叉树节点进行左右子节点交换来生成镜像树,并提供了完整的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。

           所谓数的镜像,就是指每个节点的左右子节点互换位置。列如一棵二叉树的先序遍历为:8  6  5  7  10  9  11,它的镜像树的先序 遍历则为8  10  11  9  6  7  5 。

        代码如下:

       public class BinaryTreeDemo {

    public static void main(String[] args) {
        /**
         * 构造一棵二叉树
         * */
        BinaryTreeNode root = new BinaryTreeNode(8);
        root.left = new BinaryTreeNode(6);
        root.right = new BinaryTreeNode(10);
        
        root.left.left = new BinaryTreeNode(5);
        root.left.right = new BinaryTreeNode(7);
        
        root.right.left = new BinaryTreeNode(9);
        root.right.right = new BinaryTreeNode(11);
        
        root.left.left.left = null;
        root.left.left.right = null;
        
        root.left.right.left = null;
        root.left.right.right = null;
        
        root.right.left.left = null;
        root.right.left.right = null;
        
        root.right.right.left = null;
        root.right.right.right = null;
        
        /**
         * 先序遍历二叉树
         * */
        printBinaryTree(root);
        System.out.println();
        /**
         * 求出一棵二叉树的镜像
         *
         * */
        BinaryTreeNode root1 = mirrorRecursively(root);
        printBinaryTree(root1);
        
    }

    private static BinaryTreeNode mirrorRecursively(BinaryTreeNode root) {
        if(root != null){
            BinaryTreeNode treeNode = null;
            //调换节点的左右节点
            treeNode = root.left;
            root.left = root.right;
            root.right = treeNode;
            root.left =  mirrorRecursively(root.left);
            root.right =  mirrorRecursively(root.right);
        }else{
            return null;
        }
        return root;
    }

    private static void printBinaryTree(BinaryTreeNode root) {
        if(root != null){
            
            System.out.print(root.value + "  ");
            printBinaryTree(root.left);
            printBinaryTree(root.right);
            
        }else{
            return;
        }
        
        
    }

}
/**
 *
 *二叉树的节点类
 * */
class BinaryTreeNode{
    public int value;
    public BinaryTreeNode left;
    public BinaryTreeNode right;
    
    public BinaryTreeNode(int value) {
        super();
        this.value = value;
    }
    
    public BinaryTreeNode() {
        super();
    }
    
    
}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值