二叉树的镜像

来源:互联网 发布:贝奥武夫结局知乎 编辑:程序博客网 时间:2024/06/07 00:41
package demo;import java.util.Stack;/* * 题目描述操作给定的二叉树,将其变换为源二叉树的镜像。输入描述:二叉树的镜像定义:源二叉树             8           /  \          6   10         / \  / \        5  7 9 11        镜像二叉树            8           /  \          10   6         / \  / \        11 9 7  5 */public class Offer_38 {    public void Mirror(TreeNode root) {        //所谓镜像,就是左右子树交换位置        if(root == null)            return;//若为空则直接返回        Stack<TreeNode> stack = new Stack<TreeNode>();//新建一个栈空间        stack.push(root);//将给定树入栈        while(!stack.empty()) {//若栈不为空            TreeNode node = stack.pop();//将出栈数据保存在新建的node中            if(node.left != null || node.right != null) {//若node左右均不为空                TreeNode nodeLeft = node.left;//新建左右TreeNode节点                TreeNode nodeRight = node.right;                node.left = nodeRight;//交换左右节点                node.right = nodeLeft;            }            if(node.left != null)//若左右节点不为空则入栈                stack.push(node.left);            if(node.right != null)                stack.push(node.right);        }    }    public static void main(String[] args) {        Offer_38 off = new Offer_38();        TreeNode root = new TreeNode(1);        root.left = new TreeNode(6);        root.right = new TreeNode(10);        root.left.left = new TreeNode(5);        root.left.right = new TreeNode(7);        root.right.left = new TreeNode(9);        root.right.right = new TreeNode(11);    }}
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 sunflower 向日葵代表什么意思 癸花 阳蒂照片 蒂拼音 蒂的拼音 蒂意思 蒂的意思 超高吸蒂技巧 克里斯蒂在野外 亲蒂技巧 蒂怎么读 蒂尔达斯文顿 克里斯蒂 斯卡蒂 蒂莫西柴勒梅德 马尔蒂尼 蒂头图片 并蒂意思 艾洛蒂袁 蒂环图片欣赏 蒂亚 蒂亚在线 蒂亚作品 蒂亚ipz922 蒂亚播放 蒂亚tia 蒂亚全部作品 蒂亚在线播放 蒂亚与精喷量世界第一 tia蒂亚作品中文字幕 2018蒂亚全部作品在线 2018蒂亚全部作品 2019蒂亚全部作品在线 蒂克 蒂塔万提斯 费尔蒂塔 蒂塔 蒂塔万蒂斯