zoukankan      html  css  js  c++  java
  • 剑指Offer(Java版)第二十三题:操作给定的二叉树,将其变换为源二叉树的镜像。

    /*
    操作给定的二叉树,将其变换为源二叉树的镜像。
    */
    //思路:根据二叉树中序的特点,使用栈来实现或者使用递归来实现。将镜像反转的特点和二叉树中序遍历的程序结合起来就可以实现了。

    import java.util.*;

    public class Class23 {

    static class TreeNode{
    double val;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val){
    this.val = val;
    }
    }
    //使用栈
    public void MirrorTree(TreeNode tree){
    if(tree == null){
    return;
    }
    //创建一个栈
    Stack<TreeNode> stack = new Stack<>();
    while((tree != null) && (!stack.isEmpty())){
    while(tree != null){
    TreeNode tempNode = tree.left;
    tree.left = tree.right;
    tree.right = tempNode;
    stack.push(tree);
    tree = tree.left;
    }
    if(!stack.isEmpty()){
    stack.pop();
    tree = tree.right;
    }
    }
    }
    //使用递归
    public void MirrorTree2(TreeNode tree){
    if(tree == null){
    return;
    }
    while(tree != null){
    TreeNode tempNode = tree.left;
    tree.left = tree.right;
    tree.right = tempNode;
    MirrorTree2(tree.left);
    MirrorTree2(tree.right);
    }

    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub

    }

    }

  • 相关阅读:
    装饰器模式
    doraemon的python 三元函数
    doraemon的python 文件操作
    doraemon的python 深浅拷贝和文件操作
    doraemon的python 集合
    doraemon的python 字典
    doraemon的python 列表
    doraemon 周总结1
    doraemon的python 练习
    doraemon的python之旅 整型、布尔值和字符串2
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12465707.html
Copyright © 2011-2022 走看看