# 练习
# LeetCode:226. 翻转二叉树
# 解一
var invertTree = function (root) {
if (!root) return null
let q = [root];
for (let i = 0; i < q.length; i++) {
let n = q[i];
let temp = n.left;
n.left = n.right;
n.right = temp;
n.right && q.push(n.right);
n.left && q.push(n.left)
}
return root;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 解二
var invertTree = function (root) {
if (!root) return null
return {
val:root.val,
right:invertTree(root.left),
left:invertTree(root.right)
}
};
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# LeetCode:100. 相同的树
var isSameTree = function (p, q) {
if (!p && !q) return true;
if (p && q &&
p.val === q.val
&&
isSameTree(p.left, q.left)
&&
isSameTree(p.right, q.right)
) {
return true;
}
return false
};
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# LeetCode:101. 对称二叉树
var isSymmetric = function (root) {
if (!root) return true
const isMirror = (l, r) => {
if(!l && !r) return true;
if (
l && r &&
l.val === r.val
&&
isMirror(l.left, r.right)
&&
isMirror(l.right, r.left)
) {
return true
}
return false
}
return isMirror(root.left, root.right)
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19