Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4aad0f9

Browse files
committed
添加 二叉树的迭代遍历.md Scala版本
1 parent b2be41e commit 4aad0f9

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

‎problems/二叉树的迭代遍历.md‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,71 @@ func inorderTraversal(_ root: TreeNode?) -> [Int] {
568568
return result
569569
}
570570
```
571+
Scala:
572+
```scala
573+
// 前序遍历(迭代法)
574+
object Solution {
575+
import scala.collection.mutable
576+
def preorderTraversal(root: TreeNode): List[Int] = {
577+
val res = mutable.ListBuffer[Int]()
578+
if (root == null) return res.toList
579+
// 声明一个栈,泛型为TreeNode
580+
val stack = mutable.Stack[TreeNode]()
581+
stack.push(root) // 先把根节点压入栈
582+
while (!stack.isEmpty) {
583+
var curNode = stack.pop()
584+
res.append(curNode.value) // 先把这个值压入栈
585+
// 如果当前节点的左右节点不为空,则入栈,先放右节点,再放左节点
586+
if (curNode.right != null) stack.push(curNode.right)
587+
if (curNode.left != null) stack.push(curNode.left)
588+
}
589+
res.toList
590+
}
591+
}
571592

593+
// 中序遍历(迭代法)
594+
object Solution {
595+
import scala.collection.mutable
596+
def inorderTraversal(root: TreeNode): List[Int] = {
597+
val res = mutable.ArrayBuffer[Int]()
598+
if (root == null) return res.toList
599+
val stack = mutable.Stack[TreeNode]()
600+
var curNode = root
601+
// 将左节点都入栈,当遍历到最左(到空)的时候,再弹出栈顶元素,加入res
602+
// 再把栈顶元素的右节点加进来,继续下一轮遍历
603+
while (curNode != null || !stack.isEmpty) {
604+
if (curNode != null) {
605+
stack.push(curNode)
606+
curNode = curNode.left
607+
} else {
608+
curNode = stack.pop()
609+
res.append(curNode.value)
610+
curNode = curNode.right
611+
}
612+
}
613+
res.toList
614+
}
615+
}
616+
617+
// 后序遍历(迭代法)
618+
object Solution {
619+
import scala.collection.mutable
620+
def postorderTraversal(root: TreeNode): List[Int] = {
621+
val res = mutable.ListBuffer[Int]()
622+
if (root == null) return res.toList
623+
val stack = mutable.Stack[TreeNode]()
624+
stack.push(root)
625+
while (!stack.isEmpty) {
626+
val curNode = stack.pop()
627+
res.append(curNode.value)
628+
// 这次左节点先入栈,右节点再入栈
629+
if(curNode.left != null) stack.push(curNode.left)
630+
if(curNode.right != null) stack.push(curNode.right)
631+
}
632+
// 最后需要翻转List
633+
res.reverse.toList
634+
}
635+
}
636+
```
572637
-----------------------
573638
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /