【Java数据结构】BST树(二叉搜索树)总结06(求BST树的镜像)

二叉树总结:入口

二叉树的基本操作:

1、插入,删除 操作

2、前、中、后序遍历,层序遍历

3、求BST树高度,求BST树节点个数

4、返回中序遍历第k个节点的值

5、判断一个二叉树是否是BST树,判断一个BST树是否是AVl树

6、BST树的镜像

7、把BST树满足[begin,end]区间的值放在集合中、打印出来

8、判断是否是子树

9、按层打印二叉树

BST树的镜像

前序遍历二叉树,先将根节点入栈,然后交换其左右子树,再将子树入栈以此类推。

使用递归一样是先交换根节点左右子树,再进入孩子节点,以此类推。

//求BST的镜像   交换每一颗子树的左右孩子
    public void mirror(BSTNode root){
        if(root == null){
            return;
        }
        Stack<BSTNode> stack = new Stack<BSTNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            BSTNode node = stack.pop();
            if(node.getLeft() != null||node.getRight() != null){
                BSTNode temp = node.getLeft();
                node.setLeft(node.getRight());
                node.setRight(temp);
            }
            if(node.getLeft()!=null){
                stack.push(node.getLeft());
            }
            if(node.getRight()!=null){
                stack.push(node.getRight());
            }
        }
    }
    // 递归求镜像
    public void mirror1(BSTNode root){
        if(root==null){
            return;
        }
        BSTNode temp =root.getLeft();
        root.setLeft(root.getRight());
        root.setRight(temp);
        mirror1(root.getLeft());
        mirror1(root.getRight());
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值