[剑指Offer]二叉树的镜像

题目描述


输入一个二叉树,输出它的镜像。

镜像示例如下图:

[剑指Offer]二叉树的镜像_第1张图片

解题思路


递归解法:
   
    以前序编列二叉树的每个结点,如果遍历到的结点有子节点,交换左右子节点,当交换完所有非叶子结点的左右子节点之后,就得到了二叉树的镜像。


非递归解法:

    使用队列来保存结点,每次取出队列队首结点,如果此节点不为空,则交换其左右子节点,按交换后的顺序将其左右子节点添加到队尾,直到队列中再无元素为止。

代码


递归解法:

/**
	 * 使用递归的方法将一个二叉树变成其镜像
	 * 
	 * @param root
	 * @return
	 */
	public static TreeNode getBinaryTreeMirrorRecursively(TreeNode root) {
		if (root == null)
			return null;
		if (root.left == null && root.right == null)
			return root;

		//交换左右孩子
		TreeNode tempNode = root.left;
		root.left = root.right;
		root.right = tempNode;

		root.left = getBinaryTreeMirrorRecursively(root.left);
		root.right = getBinaryTreeMirrorRecursively(root.right);

		return root;
	}


非递归解法:

/**
	 * 使用循环的方法将一个二叉树变成其镜像
	 * 
	 * @param root
	 * @return
	 */
	public static TreeNode getBinaryTreeMirrorByLoop(TreeNode root) {
		if (root == null)
			return null;
		Queue queue = new LinkedList();
		TreeNode currentNode, tempNode;

		queue.add(root);
		while (!queue.isEmpty()) {
			currentNode = queue.poll();
			if (currentNode != null) {
				//交换左右孩子
				tempNode = currentNode.left;
				currentNode.left = currentNode.right;
				currentNode.right = tempNode;
                
				//以镜像中的左右孩子顺序添加到队列中
				queue.offer(currentNode.left);
				queue.offer(currentNode.right);
			}
		}
		return root;
	}


你可能感兴趣的:(剑指Offer)