mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2024-12-27 12:56:17 +00:00
添加 Swift 代码实现
This commit is contained in:
parent
7572d7c2f7
commit
acc662b89a
@ -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()`,下面再修改一两行代码也可以实现,这里这样写是方便动画模拟,大家可以随意发挥。
|
||||
|
||||
时间复杂度 O(n), 空间复杂度O(n)
|
||||
|
Loading…
Reference in New Issue
Block a user