• 二叉树的镜像


    题目描述

      操作给定的二叉树,将其变换为源二叉树的镜像。

    二叉树的镜像定义:
    源二叉树 8 / 6 10 / / 5 7 9 11
    镜像二叉树 8 / 10 6 / / 11 9 7 5
    算法实现
    (1)递归方法
    public void Mirror(TreeNode root) {
            if(root == null){
                return;
            }
            TreeNode temp = null;
            temp = root.left;
            root.left = root.right;
            root.right = temp;
            if(root.left != null){
                Mirror(root.left);
            }
            if(root.right != null){
               Mirror(root.right);
            }
        }

      (2)非递归方法

    public void Mirror(TreeNode root) {
           if(root==null)
                return;
            Stack<TreeNode> stackNode = new Stack();
            stackNode.push(root);
            while(stackNode.size() > 0){
                TreeNode tree=stackNode.pop();
                if(tree.left!=null || tree.right!=null){
                    TreeNode ptemp=tree.left;
                    tree.left=tree.right;
                    tree.right=ptemp;
                }
                if(tree.left!=null)
                    stackNode.push(tree.left);
                if(tree.right!=null)
                    stackNode.push(tree.right);
            }
        }

    拓展:此处是在原二叉树的基础上进行镜像操作,即原二叉树的左右子数发生了交换,当题目中要求返回原二叉树的镜像但是不改变原二叉树的结构时,则需要另行考虑,有兴趣的可以自行实现,也可以私信联系我哦!

  • 相关阅读:
    微擎使用函数获取用户微信信息
    xshell连接不上linux情况一
    destoon手机端分页
    kvm安装win2012
    kvm安装ubuntu
    KVM的磁盘管理相关
    ubuntu的iptables
    kvm安装win2003
    Centos-6.4 安装mysql-5.5.14
    CentOS 6.4安装bind-9.8.2最新版(DNS服务器)
  • 原文地址:https://www.cnblogs.com/suixue/p/5818515.html
Copyright © 2020-2023  润新知