剑指offer系列(18)二叉树的镜像

题目描述

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


样例

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5


思路分析

1.获取当前节点,左节点和右节点交换顺序

2.对左节点和右节点也进行同样的操作

3.返回调整好顺序的节点

4.终止条件root==null


递归写法:交换节点 不为空则继续遍历整个树

循环写法:层序遍历的思想,利用栈和队列特性,出栈(出队)时右子树节点先入栈(入队),此题由于是求镜像,所以每层遍历从左到右,从右到左都可以,无差别,所以队列和栈都可以用在此题的解上


代码

方法一:递归

public void Mirror(TreeNode root) {
	        if (root == null) {  //边界条件 为空则无镜像的说法
				return;
			}
	        if (root.left==null && root.right==null) {
				return;
			}
	        TreeNode temp = root.left;  //定义中间变量 交换左右子树
	        root.left = root.right;
	        root.right = temp;
	        if (root.left != null) {  //递归完成对树的遍历
	        	Mirror(root.left);
	        }
	        if (root.right != null) {
	        	Mirror(root.right);
	        }
	    }

结果



方法二:栈 层序遍历 循环写法

public void Mirror(TreeNode root) {
		if (root == null) {
			return;
		}
		Stack<TreeNode> stack = new Stack<TreeNode>();
		stack.push(root);
		while ( !stack.isEmpty() ){
			TreeNode current = stack.pop();
			if (current.left != null || current.right != null) {
				TreeNode temp = current.left;
				current.left = current.right;
				current.right = temp;
			}
			if (current.left != null) {
				stack.push(current.left);
			}
			if (current.right != null) {
				stack.push(current.right);
			}
		}
	}

结果


方法三:队列 层序遍历 循环写法

public void Mirror(TreeNode root) {
		if (root == null) {
			return;
		}
		Queue<TreeNode> queue = new LinkedList<TreeNode>();
		queue.offer(root);
		while ( !queue.isEmpty() ){
			TreeNode current = queue.poll();
			if (current.left != null || current.right != null) {
				TreeNode temp = current.left;
				current.left = current.right;
				current.right = temp;
			}
			if (current.left != null) {
				queue.offer(current.left);
			}
			if (current.right != null) {
				queue.offer(current.right);
			}
		}
	}

结果




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值