forked from azl397985856/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101.symmetric-tree.js
41 lines (35 loc) · 953 Bytes
/
101.symmetric-tree.js
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
/*
* @lc app=leetcode id=101 lang=javascript
*
* [101] Symmetric Tree
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function traversal(root) {
if (!root) return [null];
return [root.val].concat(traversal(root.left)).concat(traversal(root.right));
}
function reversedTraversal(root) {
if (!root) return [null];
return [root.val].concat(reversedTraversal(root.right)).concat(reversedTraversal(root.left));
}
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
if (root === null) return true;
const left = traversal(root.left);
const right = reversedTraversal(root.right);
// 判断left 和 right 是否一致
if (left.length !== right.length) return false;
for(let i = 0; i < left.length; i++) {
if (left[i] !== right[i]) return false;
}
return true;
};