Skip to content

Commit 312a828

Browse files
author
chenzhao
committed
feat(#0101): another recursion
1 parent 46043c2 commit 312a828

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

Diff for: 0101. Symmetric Tree.js

+36-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
// \ \
1717
// 3 3
1818

19-
// 1)
19+
// 1) 递归
2020
/**
2121
* Definition for a binary tree node.
2222
* function TreeNode(val, left, right) {
@@ -30,7 +30,7 @@
3030
* @return {boolean}
3131
*/
3232
const isSymmetric = root => {
33-
if (!root.left && !root.right) {
33+
if (!root || !root.left && !root.right) {
3434
return true
3535
}
3636
const symmetric = (l, r) => {
@@ -53,3 +53,37 @@ const isSymmetric = root => {
5353
}
5454
return false
5555
}
56+
57+
// 2) 递归
58+
/**
59+
* Definition for a binary tree node.
60+
* function TreeNode(val, left, right) {
61+
* this.val = (val===undefined ? 0 : val)
62+
* this.left = (left===undefined ? null : left)
63+
* this.right = (right===undefined ? null : right)
64+
* }
65+
*/
66+
/**
67+
* @param {TreeNode} root
68+
* @return {boolean}
69+
*/
70+
const isSymmetric = root => {
71+
if (!root) {
72+
return true
73+
}
74+
const isMirror = (l, r) => {
75+
if (!l && !r) {
76+
return true
77+
}
78+
if (!l || !r || l.val !== r.val) {
79+
return false
80+
}
81+
return isMirror(l.left, r.right) && isMirror(l.right, r.left)
82+
}
83+
return isMirror(root.left, root.right)
84+
}
85+
86+
// [2,97,97,null,47,80,null,-7,null,null,-7]
87+
// [1,0]
88+
// [1]
89+
// []

0 commit comments

Comments
 (0)