diff --git "a/problems/\344\272\214\345\217\211\346\240\221\347\232\204\351\200\222\345\275\222\351\201\215\345\216\206.md" "b/problems/\344\272\214\345\217\211\346\240\221\347\232\204\351\200\222\345\275\222\351\201\215\345\216\206.md" index 875e6169df..0468b79b98 100644 --- "a/problems/\344\272\214\345\217\211\346\240\221\347\232\204\351\200\222\345\275\222\351\201\215\345\216\206.md" +++ "b/problems/\344\272\214\345\217\211\346\240\221\347\232\204\351\200\222\345\275\222\351\201\215\345\216\206.md" @@ -409,5 +409,56 @@ int* postorderTraversal(struct TreeNode* root, int* returnSize){ } ``` +Swift: +前序遍历:(144.二叉树的前序遍历) +```Swift +func preorderTraversal(_ root: TreeNode?) -> [Int] { + var res = [Int]() + preorder(root, res: &res) + return res +} +func preorder(_ root: TreeNode?, res: inout [Int]) { + if root == nil { + return + } + res.append(root!.val) + preorder(root!.left, res: &res) + preorder(root!.right, res: &res) +} +``` + +中序遍历:(94. 二叉树的中序遍历) +```Swift +func inorderTraversal(_ root: TreeNode?) -> [Int] { + var res = [Int]() + inorder(root, res: &res) + return res +} +func inorder(_ root: TreeNode?, res: inout [Int]) { + if root == nil { + return + } + inorder(root!.left, res: &res) + res.append(root!.val) + inorder(root!.right, res: &res) +} +``` + +后序遍历:(145. 二叉树的后序遍历) +```Swift +func postorderTraversal(_ root: TreeNode?) -> [Int] { + var res = [Int]() + postorder(root, res: &res) + return res +} +func postorder(_ root: TreeNode?, res: inout [Int]) { + if root == nil { + return + } + postorder(root!.left, res: &res) + postorder(root!.right, res: &res) + res.append(root!.val) +} +``` -----------------------