diff --git a/animation-simulation/二叉树/二叉树的前序遍历(栈).md b/animation-simulation/二叉树/二叉树的前序遍历(栈).md index e81749b..90fea79 100644 --- a/animation-simulation/二叉树/二叉树的前序遍历(栈).md +++ b/animation-simulation/二叉树/二叉树的前序遍历(栈).md @@ -67,3 +67,32 @@ class Solution { } ``` +Swift Code: + +```swift +class Solution { + + func preorderTraversal(_ root: TreeNode?) -> [Int] { + var list:[Int] = [] + var stack:[TreeNode] = [] + + guard root != nil else { + return list + } + stack.append(root!) + while !stack.isEmpty { + let temp = stack.popLast() + if let right = temp?.right { + stack.append(right) + } + if let left = temp?.left { + stack.append(left) + } + //这里也可以放到前面 + list.append((temp?.val)!) + } + return list + } +} +``` +