1. 题目描述
请完成一个函数,输入一个二叉树,该函数输出它的镜像
2. 解题思路
书上给了一个示意图:

显而易见,从根节点开始,交换左右子树的位置;再照这个思路向下处理子树节点。
3. 代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
class Node { constructor(value, left = null, right = null) { this.value = value this.left = left this.right = right } }
function mirrorBinaryTree(root) { if (root === null) { return }
let left = root.left root.left = root.right root.right = left
if (root.left) { mirrorBinaryTree(root.left) }
if (root.right) { mirrorBinaryTree(root.right) } }
const root = new Node(0, new Node(1, new Node(3)), new Node(2))
mirrorBinaryTree(root)
console.log(root)
|