code kata 230814

This commit is contained in:
VicRen
2023-08-14 14:23:15 +08:00
parent a515a19ad7
commit a2edce208c
2 changed files with 144 additions and 0 deletions

View File

@@ -0,0 +1,109 @@
package main
import (
"fmt"
"testing"
)
func preOrder(n *node) {
stack := MakeStack()
p := n
for p != nil || !stack.IsEmpty() {
if p != nil {
visit(p)
stack.Push(p)
p = p.left
} else {
p = stack.Pop().(*node)
p = p.right
}
}
}
func inOrder(n *node) {
stack := MakeStack()
p := n
for p != nil || !stack.IsEmpty() {
if p != nil {
stack.Push(p)
p = p.left
} else {
p = stack.Pop().(*node)
visit(p)
p = p.right
}
}
}
func postOrder(n *node) {
stack := MakeStack()
p := n
var r *node = nil
for p != nil || !stack.IsEmpty() {
if p != nil {
stack.Push(p)
p = p.left
} else {
p = stack.Top().(*node)
if p.right != nil && p.right != r {
p = p.right
stack.Push(p)
p = p.left
} else {
p = stack.Pop().(*node)
visit(p)
r = p
p = nil
}
}
}
}
func TestPreOrder(t *testing.T) {
preOrder(makeBinaryTree())
}
func TestInOrder(t *testing.T) {
inOrder(makeBinaryTree())
}
func TestPostOrder(t *testing.T) {
postOrder(makeBinaryTree())
}
func visit(n *node) {
if n == nil {
return
}
fmt.Printf("visiting node %s\n", n.value)
}
func makeBinaryTree() *node {
return &node{
left: &node{
left: &node{
value: "D",
},
right: &node{
value: "E",
},
value: "B",
},
right: &node{
left: &node{
value: "F",
},
right: &node{
value: "G",
},
value: "C",
},
value: "A",
}
}
type node struct {
value string
left *node
right *node
}

35
code_kata_230814/stack.go Normal file
View File

@@ -0,0 +1,35 @@
package main
type Stack []interface{}
func MakeStack() *Stack {
return &Stack{}
}
func (s Stack) IsEmpty() bool {
return len(s) == 0
}
func (s Stack) Len() int {
return len(s)
}
func (s Stack) Top() interface{} {
if s.IsEmpty() {
return nil
}
return s[len(s)-1]
}
func (s *Stack) Push(item interface{}) {
*s = append(*s, item)
}
func (s *Stack) Pop() interface{} {
if s.IsEmpty() {
return nil
}
ret := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return ret
}