File tree Expand file tree Collapse file tree 1 file changed +11
-24
lines changed
leetcode/0101.Symmetric-Tree Expand file tree Collapse file tree 1 file changed +11
-24
lines changed Original file line number Diff line number Diff line change @@ -17,31 +17,18 @@ type TreeNode = structures.TreeNode
17
17
*/
18
18
19
19
func isSymmetric (root * TreeNode ) bool {
20
- if root == nil {
21
- return true
22
- }
23
- return isSameTree (invertTree (root .Left ), root .Right )
24
- }
25
-
26
- func isSameTree (p * TreeNode , q * TreeNode ) bool {
27
- if p == nil && q == nil {
28
- return true
29
- } else if p != nil && q != nil {
30
- if p .Val != q .Val {
20
+ var dfs func (rootLeft , rootRight * TreeNode ) bool
21
+ dfs = func (rootLeft , rootRight * TreeNode ) bool {
22
+ if rootLeft == nil && rootRight == nil {
23
+ return true
24
+ }
25
+ if rootLeft == nil || rootRight == nil {
31
26
return false
32
27
}
33
- return isSameTree (p .Left , q .Left ) && isSameTree (p .Right , q .Right )
34
- } else {
35
- return false
36
- }
37
- }
38
-
39
- func invertTree (root * TreeNode ) * TreeNode {
40
- if root == nil {
41
- return nil
28
+ if rootLeft .Val != rootRight .Val {
29
+ return false
30
+ }
31
+ return dfs (rootLeft .Left , rootRight .Right ) && dfs (rootLeft .Right , rootRight .Left )
42
32
}
43
- invertTree (root .Left )
44
- invertTree (root .Right )
45
- root .Left , root .Right = root .Right , root .Left
46
- return root
33
+ return root == nil || dfs (root .Left , root .Right )
47
34
}
You can’t perform that action at this time.
0 commit comments