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

文章介绍了如何通过前序遍历的方法,通过交换二叉树中非叶子节点的左子树和右子树,实现二叉树的镜像转换。给出了一个`BinaryTree`类的示例代码,展示了插入和遍历操作,以及镜像转换的过程。
摘要由CSDN通过智能技术生成

考察点

树的遍历

知识点

题目

分析
我们分析算法题目的思路基本上都是归纳法,即通过举一些普通的例子来推理出算法流程,而画图又是举例子的常用手段,比如针对树或者链表画画图,针对数字类的举一些数字的例子寻找规律,很快就能得到解决问题的方案。这道题目要求树的镜像,只要谈到树我们的思维就往那几个遍历上靠,前序遍历树的过程中交换非叶子结点的左子树和右子树就可以了。

public class BinaryTree {
	Node root;

	public BinaryTree() {
		this.root = null;
	}
	public void convertMirror(Node root) {
		if (root == null) {
			return;
		}
		if (root.leftChild != null && root.rightChild != null) {
			Node tmp = root.leftChild;
			root.leftChild = root.rightChild;
			root.rightChild = tmp;
		}
		convertMirror(root.leftChild);
		convertMirror(root.rightChild);
	}
	public void insertTree(int val) {
		if (this.root == null) {
			Node root = new Node(val);
			this.root = root;
		} else {
			insertChildTree(this.root,val);
		}
	}
	public void insertChildTree(Node node,int val) {
		if (node != null && val <= node.val) {
			if (node.leftChild == null) {
				node.leftChild = new Node(val);
			} else {
				insertChildTree(node.leftChild,val);
			}
		}
		if (node != null && val > node.val) {
			if (node.rightChild == null) {
				node.rightChild = new Node(val);
			} else {
				insertChildTree(node.rightChild,val);
			}
		}
	}
	public Node getRoot() {
		return this.root;
	}
	public void prePrint(Node node) {
		if (node == null) {
			return;
		}
		System.out.print(node.val + " ");
		prePrint(node.leftChild);
		prePrint(node.rightChild);
	}
}
public class Node{
	int val;
	Node leftChild;
	Node rightChild;

	public Node(int data) {
		this.val = data;
		this.leftChild = null;
		this.rightChild = null;
	}
}
public class Nineteen {
	public static void main(String[] args) {
		BinaryTree binaryTree = new BinaryTree();
		binaryTree.insertTree(8);
		binaryTree.insertTree(6);
		binaryTree.insertTree(10);
		binaryTree.insertTree(5);
		binaryTree.insertTree(7);
		binaryTree.insertTree(9);
		binaryTree.insertTree(11);
		binaryTree.prePrint(binaryTree.getRoot());
		System.out.println();
		binaryTree.convertMirror(binaryTree.getRoot());
		binaryTree.prePrint(binaryTree.getRoot());

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值