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