《剑指offer》面试题19:二叉树的镜像

本文介绍了两种实现二叉树镜像的方法:递归法和循环法。递归法通过临时保存左子树并交换左右子树来实现;循环法则借助栈辅助,依次将右节点压入栈中并弹出进行左右子树交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。

方法一:递归

思路:去掉空树、单节点的情况,将左子树临时保存,右子树赋值给左子树,递归进行交换。

public static void MirrorRecursively(TreeNode root) {
	if (root == null)
		return ;
	if (root.left == null && root.right == null)
		return ;
	TreeNode tmp = root.left;
	root.left = root.right;
	root.right = tmp;
	if (root.left != null)
		MirrorRecursively(root.left);
	if (root.right != null)
		MirrorRecursively(root.right);
}

方法二:循环

思路:使用栈进行辅助。将树的右节点压入栈中,之后弹出进行交换左右子树。

public static void MirrorRecursively(TreeNode root) {
	// 空树或者只有一个节点
	if (root == null)
		return ;
	if (root.left == null && root.right == null)
		return ;
	
	Stack<TreeNode> stack = new Stack<TreeNode>();
	stack.push(root);
	
	TreeNode nodep = null;
	while (stack != null || nodep != null) {
		// nodep还是上一点的left或者是stack里面的节点
		if (nodep == null && !stack.isEmpty())
			nodep = stack.pop();
		if (nodep == null)
			return ;
		
		// 交换左右节点
		if (nodep.left != null || nodep.right != null) {
			TreeNode tmp = nodep.left;
			nodep.left = nodep.right;
			nodep.right = tmp;
		}
		// 右节点压栈
		if (nodep.right != null)
			stack.push(nodep.right);
		nodep = nodep.left;		// 直接赋值,while最开始会判断
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值