Skip to content

Commit 37b2a2a

Browse files
committed
添加 Swift 代码实现
1 parent da6ec4e commit 37b2a2a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

animation-simulation/二叉树/二叉树的后续遍历(Morris).md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,62 @@ class Solution {
116116
}
117117
```
118118

119+
Swift Code:
120+
121+
```swift
122+
class Solution {
123+
var list:[Int] = []
124+
func postorderTraversal(_ root: TreeNode?) -> [Int] {
125+
guard root != nil else {
126+
return list
127+
}
128+
var p1 = root, p2: TreeNode?
129+
while p1 != nil {
130+
p2 = p1!.left
131+
if p2 != nil {
132+
while p2!.right != nil && p2!.right !== p1 {
133+
p2 = p2!.right
134+
}
135+
if p2!.right == nil {
136+
p2!.right = p1
137+
p1 = p1!.left
138+
continue
139+
} else {
140+
p2!.right = nil
141+
postMorris(p1!.left)
142+
}
143+
}
144+
p1 = p1!.right
145+
}
146+
//以根节点为起点的链表
147+
postMorris(root!)
148+
return list
149+
}
150+
151+
func postMorris(_ root: TreeNode?) {
152+
let reverseNode = reverseList(root)
153+
//从后往前遍历
154+
var cur = reverseNode
155+
while cur != nil {
156+
list.append(cur!.val)
157+
cur = cur!.right
158+
}
159+
reverseList(reverseNode)
160+
}
161+
162+
func reverseList(_ head: TreeNode?) -> TreeNode? {
163+
var cur = head, pre: TreeNode?
164+
while cur != nil {
165+
let next = cur?.right
166+
cur?.right = pre
167+
pre = cur
168+
cur = next
169+
}
170+
return pre
171+
}
172+
}
173+
```
174+
119175
时间复杂度 O(n)空间复杂度 O(1)
120176

121177
总结:后序遍历比起前序和中序稍微复杂了一些,所以我们解题的时候,需要好好注意一下,迭代法的核心是利用一个指针来定位我们上一个遍历的节点,Morris 的核心是,将某节点的右子节点,看成是一条链表,进行反向遍历。

0 commit comments

Comments
 (0)