·
·
文章目录
  1. 题目介绍
  2. 复杂度
  3. 解题思路

Symmetric Tree

题目介绍

LeetCode 101. Symmetric Tree

复杂度

时间复杂度: O(n), 空间复杂度: O(n)

解题思路

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
53
54
55
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}

class Solution {
func isSymmetric(_ root: TreeNode?) -> Bool {
return isMirror(root, root)
}

func isMirror(_ left: TreeNode?, _ right: TreeNode?) -> Bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
if left?.val != right?.val {
return false
}
return isMirror(left?.right, right?.left) && isMirror(left?.left, right?.right)
}
}

class Solution2 {
func isSymmetric(_ root: TreeNode?) -> Bool {
var queue: [TreeNode?] = []
queue.append(root)
queue.append(root)
while !queue.isEmpty {
let q = queue.removeFirst()
let p = queue.removeFirst()
if q == nil && p == nil {
continue
}
if q == nil || p == nil {
return false
}
if q!.val != p!.val {
return false
}
queue.append(q!.left)
queue.append(p!.right)
queue.append(q!.right)
queue.append(p!.left)
}
return true
}
}
**版权声明**

Ivan’s Blog by Ivan Ye is licensed under a Creative Commons BY-NC-ND 4.0 International License.
叶帆创作并维护的叶帆的博客博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证

本文首发于Ivan’s Blog | 叶帆的博客博客( http://yeziahehe.com ),版权所有,侵权必究。

本文链接:http://yeziahehe.com/2020/04/12/SymmetricTree/

支持一下
扫一扫,支持yeziahehe
  • 微信扫一扫
  • 支付宝扫一扫