From 7572d7c2f75745e9b59647e89910b9107d72f410 Mon Sep 17 00:00:00 2001 From: frank-tian Date: Mon, 19 Jul 2021 23:39:19 +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 --- .../二叉树/二叉树中序遍历(迭代).md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/animation-simulation/二叉树/二叉树中序遍历(迭代).md b/animation-simulation/二叉树/二叉树中序遍历(迭代).md index adbec99..8dd15e7 100644 --- a/animation-simulation/二叉树/二叉树中序遍历(迭代).md +++ b/animation-simulation/二叉树/二叉树中序遍历(迭代).md @@ -51,5 +51,32 @@ class Solution { } ``` +Swift Code: + +```swift +class Solution { + func inorderTraversal(_ root: TreeNode?) -> [Int] { + var arr:[Int] = [] + var cur = root + var stack:[TreeNode] = [] + + while !stack.isEmpty || cur != nil { + //找到当前应该遍历的那个节点 + while cur != nil { + stack.append(cur!) + cur = cur!.left + } + //此时指针指向空,也就是没有左子节点,则开始执行出栈操作 + if let temp = stack.popLast() { + arr.append(temp.val) + //指向右子节点 + cur = temp.right + } + } + return arr + } +} +``` + ###