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
}
}

/**
* 二叉树镜像函数
* @param {Node} root
*/
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)