-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path101.对称二叉树.js
More file actions
52 lines (47 loc) · 1.24 KB
/
101.对称二叉树.js
File metadata and controls
52 lines (47 loc) · 1.24 KB
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
46
47
48
49
50
51
52
/*
* @lc app=leetcode.cn id=101 lang=javascript
*
* [101] 对称二叉树
*/
// @lc code=start
/**
* 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 leftStack = []
const rightStack = []
leftStack.push(root)
rightStack.push(root)
while(leftStack.length && rightStack.length) {
const leftNode = leftStack.pop()
const rightNode = rightStack.pop()
if(leftNode.val !== rightNode.val) {
return false
}
if(leftNode.left && rightNode.right) {
leftStack.push(leftNode.left)
rightStack.push(rightNode.right)
}
if(leftNode.right && rightNode.left) {
leftStack.push(leftNode.right)
rightStack.push(rightNode.left)
}
if(leftNode.left && !rightNode.right || !leftNode.left && rightNode.right) {
return false
}
if(leftNode.right && !rightNode.left || !leftNode.right && rightNode.left) {
return false
}
}
return leftStack.length === 0 && rightStack.length === 0
};
// @lc code=end