From ef44b3f3be86dcb2207d861dfb13d3904a35affb Mon Sep 17 00:00:00 2001 From: frank-tian Date: Mon, 19 Jul 2021 23:32:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20Swift=20=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../二叉树/二叉树的前序遍历(Morris).md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/animation-simulation/二叉树/二叉树的前序遍历(Morris).md b/animation-simulation/二叉树/二叉树的前序遍历(Morris).md index a6722b8..95a141f 100644 --- a/animation-simulation/二叉树/二叉树的前序遍历(Morris).md +++ b/animation-simulation/二叉树/二叉树的前序遍历(Morris).md @@ -103,4 +103,41 @@ class Solution { } ``` +Swift Code: + +```swift +class Solution { + func preorderTraversal(_ root: TreeNode?) -> [Int] { + var list:[Int] = [] + guard root != nil else { + return list + } + var p1 = root, p2: TreeNode? + while p1 != nil { + p2 = p1!.left + if p2 != nil { + //找到左子树的最右叶子节点 + while p2!.right != nil && p2!.right !== p1 { + p2 = p2!.right + } + //添加 right 指针,对应 right 指针为 null 的情况 + if p2!.right == nil { + list.append(p1!.val) + p2!.right = p1 + p1 = p1!.left + continue + } + //对应 right 指针存在的情况,则去掉 right 指针 + p2!.right = nil + } else { + list.append(p1!.val) + } + //移动 p1 + p1 = p1!.right + } + return list + } +} +``` + 好啦,今天就看到这里吧,咱们下期见! \ No newline at end of file