添加 Swift 代码实现

This commit is contained in:
frank-tian 2021-07-20 00:00:44 +08:00
parent da6ec4e14f
commit 37b2a2a12b

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 时间复杂度 On空间复杂度 O1
总结后序遍历比起前序和中序稍微复杂了一些所以我们解题的时候需要好好注意一下迭代法的核心是利用一个指针来定位我们上一个遍历的节点Morris 的核心是将某节点的右子节点看成是一条链表进行反向遍历 总结后序遍历比起前序和中序稍微复杂了一些所以我们解题的时候需要好好注意一下迭代法的核心是利用一个指针来定位我们上一个遍历的节点Morris 的核心是将某节点的右子节点看成是一条链表进行反向遍历