树的镜像

本文介绍了一种简单的方法来创建二叉树的镜像。通过递归地交换每个节点的左右子节点,可以轻松地实现这一目标。文章提供了一个Java实现的例子,并展示了如何通过先根遍历验证镜像是否正确生成。

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

题目:给定一棵树,反转这棵树得到树的镜像
例如:
这里写图片描述

分析:通过画图可知,得到一棵树的镜像只需要将该树的左右子树调换位置即可

代码如下:

package problem2;

/**
 * @author Hutongling
 */
public class 二叉树的镜像 {
    static void binTreeMiorr(TreeNode root){
        if(root==null)
            return ;
        TreeNode treeNode;
        if(root!=null){
            treeNode=root.leftChild;
            root.leftChild=root.rightChild;
            root.rightChild=treeNode;
            binTreeMiorr(root.getLeftChild());
            binTreeMiorr(root.getRightChild());
        } 
    }

    //先根遍历树(使用递归)
    static void inOrder(TreeNode root){
        if(root==null)
            return;
        if(root!=null){
            System.out.print(root.getValue() + " ");
            inOrder(root.getLeftChild());
            inOrder(root.getRightChild());
        }
    }
    public static void main(String[] args) {
        TreeNode paremtRoot=new TreeNode(8);
        TreeNode rootChild1=new TreeNode(8);
        TreeNode rootChild2=new TreeNode(7);
        TreeNode child1Child1=new TreeNode(9);
        TreeNode child1Child2=new TreeNode(2);
        TreeNode child12Child1=new TreeNode(4);
        TreeNode child12Child2=new TreeNode(7);

        paremtRoot.setLeftChild(rootChild1);
        paremtRoot.setRightChild(rootChild2);
        rootChild1.setLeftChild(child1Child1);
        rootChild1.setRightChild(child1Child2);
        child1Child2.setLeftChild(child12Child1);
        child1Child2.setRightChild(child12Child2);

        System.out.println("原树为(先根遍历):");
        inOrder(paremtRoot);
        System.out.println();

        binTreeMiorr(paremtRoot);
        System.out.println("镜像树为(先根遍历):");
        inOrder(paremtRoot);


    }

}

结果如下:
原树为(先根遍历):
8 8 9 2 4 7 7
镜像树为(先根遍历):
8 7 8 2 7 4 9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值