mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 二叉树的迭代遍历.md Scala版本
This commit is contained in:
@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user