题目二:
解法一:(递归)
js中可以解构赋值,交换很简单。
var invertTree = function(root) {
if (root === null) return root
let temp = root.right
root.right = invertTree(root.left)
root.left = invertTree(temp)
return root
};
或者
var invertTree = function(root) {
if (root === null) {
return null;
}
const left = invertTree(root.left);
const right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
};
// 前序遍历
var invertTree = function(root) {
if(root === null) return null;
[root.left,root.right] = [root.right,root.left];
invertTree(root.left);
invertTree(root.right);
return root;
};
// 中序遍历
var invertTree = function(root) {
if(root === null) return null;
invertTree(root.left);
[root.left,root.right] = [root.right,root.left];
invertTree(root.right);
return root;
};
// 后序遍历
var invertTree = function(root) {
if(root === null) return null;
invertTree(root.left);
invertTree(root.right);
[root.left,root.right] = [root.right,root.left];
return root;
};
解法二:(层序遍历、广度优先遍历)
var invertTree = function(root) {
const invertNode = function(root, left, right) {
let temp = left
left = right
right = temp
root.left = left
root.right = right
}
let queue = []
if(root === null) {
return root
}
queue.push(root)
while(queue.length) {
let length = queue.length
while (length--) {
let node = queue.shift()
invertNode(node, node.left, node.right)
node.left && queue.push(node.left)
node.right && queue.push(node.right)
}
}
return root
};
解法三:(深度优先遍历)
var invertTree = function(root) {
let stack = [root];
while(stack.length > 0){
let cur = stack.pop();
if(cur === null) continue;
[cur.left,cur.right] = [cur.right,cur.left];
stack.push(cur.right);
stack.push(cur.left);
}
return root;
};