二叉树的镜像
问题描述:二叉树镜像
首先考察基本功,前序遍历每个节点,交换其左右子树
本方法思想:前序遍历每个节点,如果遍历到节点有子节点,就左右交换两个节点,递归下去
持续更新...
代码附下
Java实现:
package 二叉树镜像;
/**
* 二叉树镜像
* @author user
*思路:前序遍历每个节点,如果遍历到节点有子节点,就左右交换两个节点
*递归下去
*/
二叉树的数据结构:
public class BinaryTree {
int val;
BinaryTree left = null;
BinaryTree right = null;
public BinaryTree(int val) {
this.val = val;
}
}
public class Mirror {
public static void main(String[] args) {
/**
* 构建一棵二叉树
*/
BinaryTree rootA = new BinaryTree(8);
rootA.left = new BinaryTree(8);
rootA.right = new BinaryTree(7);
rootA.left.left = new BinaryTree(9);
rootA.left.right = new BinaryTree(2);
rootA.left.right.left = new BinaryTree(4);
rootA.left.right.right = new BinaryTree(7);
MirrorTree(rootA);
System.out.println(rootA.val);
System.out.println(rootA.left.val);
System.out.println(rootA.right.val);
System.out.println(rootA.right.right.val);
}
//思想:交换左右子树
public static void MirrorTree(BinaryTree node) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
return;
}
// 交换左子树和右子树
BinaryTree temp = node.left;
node.left = node.right;
node.right = temp;
//递归镜像其左右子树
MirrorTree(node.left);
MirrorTree(node.right);
}
}
持续更新...欢迎赞赏!![](https://i-blog.csdnimg.cn/blog_migrate/ca0cc5c488ad24501c0bbddad6302b17.png)
主页:https://blog.csdn.net/ustcer_93lk/article/details/80374008
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。