添加 Swift 代码实现

pull/34/head
frank-tian 2021-07-20 00:00:44 +08:00
parent da6ec4e14f
commit 37b2a2a12b
1 changed files with 56 additions and 0 deletions

View File

@ -116,6 +116,62 @@ class Solution {
}
```
Swift Code
```swift
class Solution {
var list:[Int] = []
func postorderTraversal(_ root: TreeNode?) -> [Int] {
guard root != nil else {
return list
}
var p1 = root, p2: TreeNode?
while p1 != nil {
p2 = p1!.left
if p2 != nil {
while p2!.right != nil && p2!.right !== p1 {
p2 = p2!.right
}
if p2!.right == nil {
p2!.right = p1
p1 = p1!.left
continue
} else {
p2!.right = nil
postMorris(p1!.left)
}
}
p1 = p1!.right
}
//以根节点为起点的链表
postMorris(root!)
return list
}
func postMorris(_ root: TreeNode?) {
let reverseNode = reverseList(root)
//从后往前遍历
var cur = reverseNode
while cur != nil {
list.append(cur!.val)
cur = cur!.right
}
reverseList(reverseNode)
}
func reverseList(_ head: TreeNode?) -> TreeNode? {
var cur = head, pre: TreeNode?
while cur != nil {
let next = cur?.right
cur?.right = pre
pre = cur
cur = next
}
return pre
}
}
```
On O1
Morris