添加 二叉树的统一迭代法.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-19 10:19:22 +08:00
parent aafc18ee12
commit 648014b28a

View File

@ -591,6 +591,80 @@ function postorderTraversal(root: TreeNode | null): number[] {
return res; 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
}
}
```
----------------------- -----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div> <div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>