From 648014b28a54e953d335e822d7e7a5f98a82e3ea Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Thu, 19 May 2022 10:19: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=E7=BB=9F=E4=B8=80=E8=BF=AD=E4=BB=A3=E6=B3=95?= =?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的统一迭代法.md | 74 +++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index f6edf586..9ca6ac39 100644 --- a/problems/二叉树的统一迭代法.md +++ b/problems/二叉树的统一迭代法.md @@ -591,6 +591,80 @@ function postorderTraversal(root: TreeNode | null): number[] { return res; }; ``` +Scala: +```scala +// 前序遍历 +object Solution { + import scala.collection.mutable + def preorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + val stack = mutable.Stack[TreeNode]() + if (root != null) stack.push(root) + while (!stack.isEmpty) { + var curNode = stack.top + if (curNode != null) { + stack.pop() + if (curNode.right != null) stack.push(curNode.right) + if (curNode.left != null) stack.push(curNode.left) + stack.push(curNode) + stack.push(null) + } else { + stack.pop() + res.append(stack.pop().value) + } + } + res.toList + } +} +// 中序遍历 +object Solution { + import scala.collection.mutable + def inorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + val stack = mutable.Stack[TreeNode]() + if (root != null) stack.push(root) + while (!stack.isEmpty) { + var curNode = stack.top + if (curNode != null) { + stack.pop() + if (curNode.right != null) stack.push(curNode.right) + stack.push(curNode) + stack.push(null) + if (curNode.left != null) stack.push(curNode.left) + } else { + // 等于空的时候好办,弹出这个元素 + stack.pop() + res.append(stack.pop().value) + } + } + res.toList + } +} + +// 后序遍历 +object Solution { + import scala.collection.mutable + def postorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + val stack = mutable.Stack[TreeNode]() + if (root != null) stack.push(root) + while (!stack.isEmpty) { + var curNode = stack.top + if (curNode != null) { + stack.pop() + stack.push(curNode) + stack.push(null) + if (curNode.right != null) stack.push(curNode.right) + if (curNode.left != null) stack.push(curNode.left) + } else { + stack.pop() + res.append(stack.pop().value) + } + } + res.toList + } +} +``` -----------------------