101\. 对称二叉树
# 101. 对称二叉树 (opens new window)
# Description
Difficulty: 简单
Related Topics: 树 (opens new window), 深度优先搜索 (opens new window), 广度优先搜索 (opens new window), 二叉树 (opens new window)
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
1
2
2
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
1
2
2
提示:
- 树中节点数目在范围
[1, 1000]
内 -100 <= Node.val <= 100
**进阶:**你可以运用递归和迭代两种方法解决这个问题吗?
# Solution
Language: JavaScript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
// 方法一:递归
var isSymmetric = function(root) {
const check = (p, q) => {
if (!p & !q) return true
if (!p || !q) return false
return p.val === q.val && check(p.left, q.right) && check(p.right, q.left)
}
return check(root, root)
};
var isSymmetric = function(root) {
if (!root) return true
const check = (left, right) => {
if (!left && !right) return true
if (!left || !right) return false
return left.val === right.val && check(left.left, right.right) && check(left.right, right.left)
}
return check(root.left, root.right)
};
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
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