From 52ba6c2b35639233668d59eef75e41ceaf6d39bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Tue, 14 Dec 2021 13:29:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86=20Swift?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 51 ++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 875e6169..0468b79b 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.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) +} +``` -----------------------