题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
相关知识
二叉树的镜像定义:
源二叉树
镜像二叉树
思路
1.有关二叉树的算法问题,一般都可以通过递归来解决。那么写一个正确的递归程序,首先一定要分析正确递归结束的条件。
2.先前序遍历这棵树的每个结点,如果遍历到的结点有子结点,就交换它的两个子节点;
3.当交换完所有的非叶子结点的左右子结点之后,就得到了树的镜像
代码
//1.第一种方法
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function Mirror(root)
{
if(root === null) {
return;
}
var temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
//2.或者下面代码
function Mirror(root) {
if (root === null) return;
Mirror(root.left);
Mirror(root.right);
[root.left, root.right] = [root.right, root.left];
return root;
}
//3.感觉下面代码好理解一点
/*
题目:
请完成一个函数,输入一棵二叉树,该函数输出它的镜像。
*/
function TreeNode(val) {
this.val = val;
this.left = null;
this.right = null;
}
/*
思路:这个题目需要修改原来的树
先前序遍历这棵树的每个节点,如果遍历到的节点有子节点,就交换它的两个子节点
*/
function mirror(root) {
//从上至下的交换,直接执行,没有返回值
if(!root) {
return;
}
if(!root.left && !root.right) {
return;
}
let temp = root.left;
root.left = root.right;
root.right = temp;
if(root.left) {
mirror(root.left);
}
if(root.right) {
mirror(root.right);
}
}
参考文章:
https://www.cnblogs.com/echovic/p/6437152.html
https://www.cnblogs.com/wuguanglin/p/Mirror.html
https://github.com/DavidChen93/-offer-JS-/blob/master/27.1 二叉树的镜像.js