本质还是节点的左节点和右节点的交换
- 通过递归交换节点的左右节点
- 通过层级遍历然后交换左右节点
//递归写法function mirrorTree(root){//递归结束条件if(root){[root.left,root.right] = [root.right,root.left];mirrorTree(root.left);mirrorTree(root.right);}return root;}
function mirrorTree(root) { //用个栈维护迭代 let stack = []; stack.push(root); while (stack.length > 0) { let node = stack.pop(); if (node == null) continue;//为什么不是val,因为如果是叶子节点,直接就是null,非null的都是对象 //本质交换 [node.left, node.right] = [node.right, node.left]; //左右子节点继续压入栈 stack.push(node.left); stack.push(node.right); } //返回结果 return root; }
