二叉树的镜像

题目描述

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

输入描述:

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5
来源牛客。
 1     public void Mirror(TreeNode root) {
 2         /*
 3         if(root == null) return;
 4         //递归很好实现,一层一层把左子树和右子数节点对换!
 5         TreeNode temp = root.left;
 6         root.left = root.right;
 7         root.right = temp;
 8         Mirror(root.left);
 9         Mirror(root.right);
10         */
11         //使用非递归的方法实现,眼熟
12         if(root == null) return;
13         //定义一个栈记录节点
14         Stack<TreeNode> stack = new Stack<TreeNode>();
15         stack.push(root);
16         while(!stack.isEmpty()){
17             TreeNode tree = stack.pop();
18             if(tree.left != null || tree.right != null){
19                 TreeNode temp = tree.left;
20                 tree.left = tree.right;
21                 tree.right = temp;
22             }
23             if(tree.left != null) stack.push(tree.left);
24             if(tree.right != null) stack.push(tree.right);
25         }
26     }

 

 

转载于:https://www.cnblogs.com/blog-of-zxf/p/11396752.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值