题链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/
题描述:
解题思路:
第一种方法:层序遍历树,将每个节点的左右子节点读出来并变成另一棵树的子节点。最后返回新树根节点即可。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var mirrorTree = function(root) {
if (root == null) {
return null;
}
let resNode = new TreeNode(root.val);
let resBf = [resNode];
let bf = [root];
while (bf.length > 0) {
let temp = [];
let resTemp = [];
for (let i = 0; i < bf.length; i++) {
if (bf[i].right != null) {
temp.push(bf[i].right);
resBf[i].left = new TreeNode(bf[i].right.val);
resTemp.push(resBf[i].left);
}
if (bf[i].left != null) {
temp.push(bf[i].left);
resBf[i].right = new TreeNode(bf[i].left.val);
resTemp.push(resBf[i].right);
}
}
bf = temp;
resBf = resTemp;
}
return resNode;
};
时间复杂度:O(n)
空间复杂度:O(n)
第二种方法:依旧层序遍历整棵树,将每个节点的左右子节点互换即可。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var mirrorTree = function(root) {
if (root == null) {
return null;
}
let bf = [root];
while (bf.length > 0) {
let temp = [];
for (let i = 0; i < bf.length; i++) {
if (bf[i] != null) {
if (bf[i].left !=null || bf[i].right != null) {
let tNode = bf[i].left;
bf[i].left = bf[i].right;
bf[i].right = tNode;
temp.push(bf[i].left);
temp.push(bf[i].right);
}
}
}
bf = temp;
}
return root;
};
时间复杂度:O(n)
空间复杂度:O(n)