添加 Swift 代码实现

This commit is contained in:
frank-tian 2021-07-19 23:49:48 +08:00
parent 7572d7c2f7
commit acc662b89a

View File

@ -71,6 +71,39 @@ class Solution {
}
```
Swift Code
```swift
class Solution {
func postorderTraversal(_ root: TreeNode?) -> [Int] {
var list:[Int] = []
var stack:[TreeNode] = []
var cur = root, preNode: TreeNode?
while !stack.isEmpty || cur != nil {
//和之前写的中序一致
while cur != nil {
stack.append(cur!)
cur = cur!.left
}
//1.出栈可以想一下这一步的原因
cur = stack.popLast()
//2.if 里的判断语句有什么含义
if cur!.right === nil || cur!.right === preNode {
list.append(cur!.val)
//更新下 preNode也就是定位住上一个访问节点
preNode = cur
cur = nil
} else {
//3.再次压入栈和上面那条 1 的关系
stack.append(cur!)
cur = cur!.right
}
}
return list
}
}
```
当然也可以修改下代码逻辑将 `cur = stack.pop()` 改成 `cur = stack.peek()`下面再修改一两行代码也可以实现这里这样写是方便动画模拟大家可以随意发挥
时间复杂度 On, 空间复杂度On