From 4aad0f9ca58c0188248af5a1043a21722aae0129 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Wed, 18 May 2022 17:26:22 +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=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86.md=20Sca?= =?UTF-8?q?la=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的迭代遍历.md | 65 ++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index 13ba5f1e..fac30f99 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -568,6 +568,71 @@ func inorderTraversal(_ root: TreeNode?) -> [Int] { return result } ``` +Scala: +```scala +// 前序遍历(迭代法) +object Solution { + import scala.collection.mutable + def preorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + if (root == null) return res.toList + // 声明一个栈,泛型为TreeNode + val stack = mutable.Stack[TreeNode]() + stack.push(root) // 先把根节点压入栈 + while (!stack.isEmpty) { + var curNode = stack.pop() + res.append(curNode.value) // 先把这个值压入栈 + // 如果当前节点的左右节点不为空,则入栈,先放右节点,再放左节点 + if (curNode.right != null) stack.push(curNode.right) + if (curNode.left != null) stack.push(curNode.left) + } + res.toList + } +} +// 中序遍历(迭代法) +object Solution { + import scala.collection.mutable + def inorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ArrayBuffer[Int]() + if (root == null) return res.toList + val stack = mutable.Stack[TreeNode]() + var curNode = root + // 将左节点都入栈,当遍历到最左(到空)的时候,再弹出栈顶元素,加入res + // 再把栈顶元素的右节点加进来,继续下一轮遍历 + while (curNode != null || !stack.isEmpty) { + if (curNode != null) { + stack.push(curNode) + curNode = curNode.left + } else { + curNode = stack.pop() + res.append(curNode.value) + curNode = curNode.right + } + } + res.toList + } +} + +// 后序遍历(迭代法) +object Solution { + import scala.collection.mutable + def postorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + if (root == null) return res.toList + val stack = mutable.Stack[TreeNode]() + stack.push(root) + while (!stack.isEmpty) { + val curNode = stack.pop() + res.append(curNode.value) + // 这次左节点先入栈,右节点再入栈 + if(curNode.left != null) stack.push(curNode.left) + if(curNode.right != null) stack.push(curNode.right) + } + // 最后需要翻转List + res.reverse.toList + } +} +``` -----------------------