// 反转二叉树
function revertTree(root) {
if (root) {
[root.left, root.right] = [root.right, root.left];
revertTree(root.left);
revertTree(root.right);
};
return root;
}
var tree = {
value: 1,
left: {
value: 2,
left: {
value: 4
}
},
right: {
value: 3,
left: {
value: 5,
left: {
value: 7
},
right: {
value: 8
}
},
right: {
value: 6
}
}
}
// console.log(revertTree(tree));
function revertTree(root) {
if (root) {
[root.left, root.right] = [root.right, root.left];
revertTree(root.left);
revertTree(root.right)
}
return root;
}
function Mirror(node){
if(!node){
throw new Error('empty tree')
}
var queue = [];
queue.push(node);
while(queue.length !== 0) {
// 1 先进先出,但不要node = queue.shift(),否则return node为undefined
var current = queue.shift();
if(current) {
// 2 交换左右节点
var temp = current.left;
current.left = current.right;
current.right = temp;
if (current.left) queue.push(current.left)
if (current.right) queue.push(current.right);
}
}
// 3 返回反转后的tree
return node
}
var invertTreeMinor = function(root) {
let stack = [root];
let current = null;
let temp = null;
while( current = stack.pop() ){
temp = current.right;
current.right = current.left;
current.left = temp;
if (current.right) {
stack.push(current.right);
}
if (current.left) {
stack.push(current.left);
}
}
return root
};
console.log('origin', invertTreeMinor(tree));
var invertTree = function(root) {
var queue = [];
queue.push(root);
var curNode = null;
while((curNode = queue.shift()) != null){
//switch curNode left and right
// var tmp = curNode.left;
// curNode.left = curNode.right;
// curNode.right = tmp;
[curNode.left, curNode.right] = [curNode.right, curNode.left];
if (curNode.left !== null){
queue.push(curNode.left);
}
if (curNode.right !== null){
queue.push(curNode.right);
}
}
return root;
};
// console.log('new', invertTree(tree));
console