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 648014b

Browse files
committed
添加 二叉树的统一迭代法.md Scala版本
1 parent aafc18e commit 648014b

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

‎problems/二叉树的统一迭代法.md‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,80 @@ function postorderTraversal(root: TreeNode | null): number[] {
591591
return res;
592592
};
593593
```
594+
Scala:
595+
```scala
596+
// 前序遍历
597+
object Solution {
598+
import scala.collection.mutable
599+
def preorderTraversal(root: TreeNode): List[Int] = {
600+
val res = mutable.ListBuffer[Int]()
601+
val stack = mutable.Stack[TreeNode]()
602+
if (root != null) stack.push(root)
603+
while (!stack.isEmpty) {
604+
var curNode = stack.top
605+
if (curNode != null) {
606+
stack.pop()
607+
if (curNode.right != null) stack.push(curNode.right)
608+
if (curNode.left != null) stack.push(curNode.left)
609+
stack.push(curNode)
610+
stack.push(null)
611+
} else {
612+
stack.pop()
613+
res.append(stack.pop().value)
614+
}
615+
}
616+
res.toList
617+
}
618+
}
619+
620+
// 中序遍历
621+
object Solution {
622+
import scala.collection.mutable
623+
def inorderTraversal(root: TreeNode): List[Int] = {
624+
val res = mutable.ListBuffer[Int]()
625+
val stack = mutable.Stack[TreeNode]()
626+
if (root != null) stack.push(root)
627+
while (!stack.isEmpty) {
628+
var curNode = stack.top
629+
if (curNode != null) {
630+
stack.pop()
631+
if (curNode.right != null) stack.push(curNode.right)
632+
stack.push(curNode)
633+
stack.push(null)
634+
if (curNode.left != null) stack.push(curNode.left)
635+
} else {
636+
// 等于空的时候好办,弹出这个元素
637+
stack.pop()
638+
res.append(stack.pop().value)
639+
}
640+
}
641+
res.toList
642+
}
643+
}
594644

645+
// 后序遍历
646+
object Solution {
647+
import scala.collection.mutable
648+
def postorderTraversal(root: TreeNode): List[Int] = {
649+
val res = mutable.ListBuffer[Int]()
650+
val stack = mutable.Stack[TreeNode]()
651+
if (root != null) stack.push(root)
652+
while (!stack.isEmpty) {
653+
var curNode = stack.top
654+
if (curNode != null) {
655+
stack.pop()
656+
stack.push(curNode)
657+
stack.push(null)
658+
if (curNode.right != null) stack.push(curNode.right)
659+
if (curNode.left != null) stack.push(curNode.left)
660+
} else {
661+
stack.pop()
662+
res.append(stack.pop().value)
663+
}
664+
}
665+
res.toList
666+
}
667+
}
668+
```
595669
-----------------------
596670
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

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