题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
样例
二叉树的镜像定义:源二叉树
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);
}
}
}
结果