zoukankan      html  css  js  c++  java
  • 二叉树的镜像

    题目描述

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

    二叉树的镜像定义:
    源二叉树 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);
            }
        }

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

  • 相关阅读:
    LeetCode 338. 比特位计数
    LeetCode 208. 实现 Trie (前缀树)
    初识restful api接口
    破解 Navicat Premium 12
    ES6 Reflect的认识
    ES6 WeakMap和WeakSet的使用场景
    sublime 注释模版插件DocBlockr的使用
    js call方法的使用
    ES6 Generator的应用场景
    ES6 Symbol的应用场景
  • 原文地址:https://www.cnblogs.com/suixue/p/5818515.html
Copyright © 2011-2022 走看看