LeetCode-101. Symmetric Tree

问题描述

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100

解答

方法一:递归
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
/*
* @Description: 101. Symmetric Tree
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 递归
* @param {TreeNode} root
* @return {boolean}
*/
const isSymmetric = function (root) {
if (!root) {
return true
}

const dfs = (leftNode, rightNode) => {
if (!leftNode && !rightNode) {
return true
}
if (!leftNode || !rightNode || leftNode.val !== rightNode.val) {
return false
}
return dfs(leftNode.left, rightNode.right) && dfs(leftNode.right, rightNode.left)
}
return dfs(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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
* @Description: 101. Symmetric Tree
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 迭代
* @param {TreeNode} root
* @return {boolean}
*/
const isSymmetric = function (root) {
if (!root) {
return true
}
let queue = []
queue.push(root.left)
queue.push(root.right)

while (queue.length) {
let leftNode = queue.shift()
let rightNode = queue.shift()

if (!leftNode && !rightNode) {
continue
}
if (!leftNode || !rightNode || leftNode.val !== rightNode.val) {
return false
}

queue.push(leftNode.left)
queue.push(rightNode.right)

queue.push(leftNode.right)
queue.push(rightNode.left)
}
return true
}