題目:給定一個二叉樹,將該二叉樹鏡像輸出
思路:畫圖即可知道左右子節點分別交換可得
let tree = {
value:0,
left:{
value:1,
left:{
value:3,
left:{
value:7
},
right:{
value:8
}
},
right:{
value:4
}
},
right:{
value:2,
left:{
value:5
},
right:{
value:6
}
}
};
// let show = root=>{
// //前序遍歷二叉樹
// console.log(root);
// root.left && show(root.left)
// root.right && show(root.right)
// }
let bt = {
value:'',
p(root){
//前序遍歷二叉樹
if(!typeofTree(root)){
return false;
}
this.value += root.value + ' ';
root.left && this.p(root.left)
root.right && this.p(root.right)
},
print(root){
this.p(root);
console.log(this.value);
this.value = '';
}
}
bt.print(tree);
let reverseTree = root => {
if(!typeofTree(root)){
return false;
}
[root.left,root.right] = [root.right,root.left];
// let temp = root.left;
// root.left = root.right
// root.right = temp;
root.left && reverseTree(root.left)
root.right && reverseTree(root.right)
}
console.log('------------------');
reverseTree(tree);
bt.print(tree);
//魯棒性
function typeofTree(root){
return '[object Object]'=== Object.prototype.toString.call(root)
}
由於js中表示二叉樹頗爲不易,使用對象模擬出一個二叉樹,也可以使用數組的方式來模擬出二叉樹
正常遍歷使用show函數即可.