mirror of
				https://github.com/chefyuan/algorithm-base.git
				synced 2025-10-31 11:41:32 +00:00 
			
		
		
		
	添加 Swift 代码实现
This commit is contained in:
		| @@ -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 | ||||||
|  |     } | ||||||
|  | } | ||||||
|  | ``` | ||||||
|  |  | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user